0

I have a C++ DLL which exports functions that 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 declared 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 memory sequence is A B C D E F G, darray etc. ), and as a result the call to the DLL function returns erroneous results.

What did I miss? Is the mat declaration wrong? is there another attribute to declare in order to get the right parameter sequence into memory?

Thanks.

Darkzaelus
  • 2,059
  • 1
  • 15
  • 31
user346134
  • 11
  • 1
  • Please include your C# struct definition in your question – shf301 Jun 02 '13 at 21:03
  • 1
    As shf301 says, you need to include the C# struct definition in your question, but at first glance, `SafeArray` is not the right choice for `mat`. See if [this answer](http://stackoverflow.com/a/6197651/351301) helps. – anton.burger Jun 02 '13 at 21:41
  • The c# struct: [StructLayout(LayoutKind.Sequential)] public struct stIn {public double A; public double B; public double C; public int D; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public double [] dArray; public double dArr2; public double E; [MarshalAs(UnmanagedType.SafeArray)]public double [,] mat; public double F; public int G;} – user346134 Jun 03 '13 at 06:21

1 Answers1

1

Thanks to shambulator's link i have realized the error was indeed in [,] mat attribute. It should be declared as [MarshallAs(UnmanagedType.ByValArray, SizeConst = 25)] 25 Is the rows multiply with columns - mat [5,5].

user346134
  • 11
  • 1