Marshalling/unmarshalling struct containing array of structs
While handling a change request I stumbled into this very peculiar scenario. I had a structure which had array of structs and I had to read/write this in a file. So to and from buffer conversions, I knew marshalling will be most effective.
I had previously used it very effectively for CAN communication.
So I had to google a bit n found how to handle this peculiar case. Below is the code.
[StructLayout(LayoutKind.Sequential)]
public struct tagX
{
public UInt32 a;
public UInt32 b;
}
[StructLayout(LayoutKind.Sequential)]
public struct tagY
{
public UInt32 x;
public UInt32 y;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 20)]
public tagX[] stX;
}
To initialize this:
tagY stY = new tagY();
StY.stX = new tagX[20]; // Ensure size of array is equal to size const supplied in marshalAs directive.
Then on this object we can run marshalling / unmarshalling routines.