Common Language Runtime
Interop - Array structure inside structure
Question:
Hi
I'm trying to interop with a dll written in C with this structures defined:
struct block{
enum b binstance;
char i_mtr[4][4];
}
struct frame{
sruct block block f1[MAX_MB_NR];
}
And then I need to call this function:
int get_frame_stats(struct frame *n);
I already understood I should declare a class in my C# program and use [In/Out] when calling the function. The other struct fields, not displayed here, are straightforward but these ones I can t deal with. I can change a little bit these structures in the C dll if convinient.
Thanks!
Answer1:
Try something like this:
private const int MAX_MB_NR = 42;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct mtrElem {
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public char[] mtrDim1;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct block {
int bInstance;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public mtrElem[] i_mtr;
}
[StructLayout(LayoutKind.Sequential)]
public struct frame {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_MB_NR)]
block[] blocks;
}
Hans Passant., Madison, WI.
Answer2:
If I use classes instead of structs, what should alter in:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_MB_NR)]
block[] blocks;
Answer3:
No change is needed, it works the same way inside a class definition. Please be specific about "it's not working well".
Hans Passant., Madison, WI.
Answer4:
well, I am initializing the member in tho objects before I send them to the unmanaged functions and when I debug the program with a breakpoint in the unmanaged function the information on each structure inside the vector does not match the initialization...
I was now thinking... I think it could be because in the native code I have an array of structures and in the unmanaged an array of objects ( which "behave" as pointer to structures)?
Answer5:
You may have a member alignment problem. That's controlled by the StructLayoutAttribute.Pack member, it's default is 8 which matches the default #pragma pack() value of the C/C++ compiler. Look at the structure data with Debug + Windows + Memory 1 and check if the values are there but offset from where the native code expects them to be.
Hans Passant., Madison, WI.
Answer6:
It is working. thank u for helping!