在C#和C之间传递对象

use*_*002 2 c c# dll struct unmanaged

我的应用程序包含带有非托管C dll调用的C#代码.在我的C#代码中,我有一个对象/类,其属性是系统类型,如string和int以及我定义的其他对象.

我想将这个复杂的(Graph.cs)对象传递给我的C(dll)代码,你会在这里建议什么实现?

我已经尝试过移动结构但是我没有使用除了string和int之外的任何东西.

谢谢.

码:

public Class Grpah {

    TupleCollection m_TupleCollection;
    int m_nGeneralIndex;       
    bool m_bPrintWRF;
    string m_sLink;  
}

public Class TupleCollection {

    IList<Tuple> _collection;

}     

public Class Tuple {

    Globals.TupleType m_ToppleType;        
    ArrayList m_Parameters;

}

public class TupleArgs {

    public string Value { get; set; }       
    public Globals.PAS PAS;
    public RefCollection RefCollection { get; set; }
    public int Time{ get; set; }      

}

public class RefCollection {

    public List<int> SynSet{ get; set; } 
    public Globals.PAS PAS;

}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 6

尝试:

如何:使用PInvoke的Marshal结构

我认为最简单的方法是修改本机代码,使其能够使用CLR类型.

现在,你几乎肯定会使用Visual Studio,希望它是VS2005或更高版本.这意味着虽然您现有的本机代码在C中,但您可以选择深入研究一点C++.不仅如此 - 您还拥有C++/CLI.

所以我会创建一个新的C++/CLI DLL,并将你的C库链接到它,以便它可以调用C代码.然后在C++/CLI库中编写一个精简的转换层:它将公开真正的CLR类(用其编写ref class),并将调用本机C代码.

例如在C标题中:

void do_something_with_foo_data(int a, int b, int c);
Run Code Online (Sandbox Code Playgroud)

在C++/CLI中:

public ref class FooWrapper
{
    static void DoSomethingWithFoo(Foo ^foo)
    {
        // pick apart the Foo class and pass the pieces on to the C function

        do_something_with_foo_data(foo->A, foo->B, foo->C);
    }
};
Run Code Online (Sandbox Code Playgroud)

在C#中:

public class Foo
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
}

...

var foo = new Foo { A = 1, B = 2, C = 3 };
FooWrapper.DoSomethingWithFoo(foo);
Run Code Online (Sandbox Code Playgroud)