Zé Carlos
Zé Carlos

Reputation: 3807

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;

type 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.

Upvotes: 0

Views: 203

Answers (2)

Zach Johnson
Zach Johnson

Reputation: 24232

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));
}

Upvotes: 0

nonoitall
nonoitall

Reputation: 1292

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

    }

}

Upvotes: 0

Related Questions