I have a "C" struct which is defined as:
typedef unsigned char tUI8;
typedef struct
{
tUI8 Mode;
tUI8 Data[16];
} TestStruct;
And a function which takes a pointer to this structure and fill the data:
void FillTest(tUI8 Mode, TestStruct *s);
To PInvoke to this function, I wrote the C# code as:
[StructLayout(LayoutKind.Sequential)]
struct TestStruct
{
public byte Mode;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] Data;
}
static class NativeTest
{
[DllImport("Native.dll")]
public static extern void FillTest(byte mode, ref TestStruct s);
}
This works but I suspect that during the PInvoke marshaller is copying the struct during call and return instead of pinning it. I can say that because even if I don't initialize the struct, it works fine.
TestStruct s;
//here s.Data == null!
NativeTest.FillTest(10, ref s); //<<< I expected an error here
//here s.Data points to a valid byte[] of length 16
Console.WriteLine(BitConverter.ToString(s.Data));
My question is how can I define a PInvoke signature, using either struct or class, which avoid copying the data during marshalling?