Sunday, June 2, 2013

Interoperability c c# struct sequence

Interoperability c c# struct sequence

I have a C++ DLL which exports functions which use structs as input and output
i want to call the dll from a C# application. the struct definition in c++ looks something like this:
struct stIn

{

double A;

double B;

double C;

int D;

double dArray[3];

double dArra2;


double E;

double mat[10][4];

double F;

int G;

}
I have declared a C# struct with the LayoutKind.Sequential attribute.
The arrays in the struct are declared with [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] attribute
The mat is declare with [MarshalAs(UnmanagedType.SafeArray)].
I Have Noticed that the array layout in the memory is not in the order of the declaration - the arrays are at the end of the "memory chunk" of the struct (the mempry sequence is A B C D E F G, darray etc. ), and as a result the call to the dll function return erroneous results.
What do i miss? Is the mat declaration wrong? is there another attribute to decalre in order to get the right parameter sequence in the memory?
thanks