Exchange structures (envolving pointers to other structures) between C and C#
I want to use PInvoke to bring to managed side something this:
(C code)
typedef struct{
//some fields... } A;ty开发者_Python百科pe struct{
A* a; } B;int getB(B* destination){ //destionation will be an output parameter to C#
//puts an B in 'destination' return 0; }
Now, I need a way to tell managed side how to marshalling B from C to C# structure or class. I've tryed many things such as IntPtr fields, MarchalAs atributes, but with no success. I will not expose here the code that I've tryed to keep the question simple. However i could do it as long answers arrive.
If it were me, I would just use unsafe code and use pointers on the C# side:
public unsafe class UnmanagedStuff {
public struct A {
// some fields
}
public struct B {
public A* a;
}
// Add appropriate PInvoke attribute here
public static extern int getB(B* destination);
public static void UseBForSomething() {
B b;
getB(&b);
// Do something with b
}
}
You can do that using the Marshal class.
// Define a C# struct to match the unmanaged one
struct B
{
IntPtr a;
}
[DllImport("dllName")]
extern int getB(IntPtr destination);
B GetB()
{
IntPtr ptrToB = IntPtr.Zero;
getB(ptrToB);
return (B)Marshal.PtrToStructure(ptrToB, typeof(B));
}
精彩评论