简体   繁体   中英

Interoperability c c# struct sequence

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 ABCDEFG, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM