How to convert structures to a byte array in C#?
I have 2 structures below:
public struct HeaderCommand
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = SIZE_HEADER_COMMAND)] public byte[] byteSize;
public HeaderCommandStruct val;
}
public struct HeaderCommandStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] public char[] robotName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public char[] robotVersion;
public byte stepInfo;
public byte sof;
public int invokeId;
public int dataSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public char[] reserved;
public int cmdId;
}
I'd like to convert HeaderCommand Structure to byte array using StructureToByte Method below.
public static byte[] StructureToByte(HeaderCommand data)
{
int dataSize = Marshal.SizeOf(data);
byte[] arr = new byte[dataSize];
IntPtr ptr = Marshal.AllocHGlobal(dataSize);
Marshal.StructureToPtr(data, ptr, false);
Marshal.Copy(ptr, arr, 0, dataSize);
Marshal.FreeHGlobal(ptr);
return arr;
}
When I run the code, an exception "System.ArgumentException" is thrown.
I guess the problem is the size of byte array is different from Headercommand
structure.
the Exception occurs at the line 'Marshal.StrucutureToPtr(data,ptr,false)'
Am I missing something or is it wrong to check the structure size by using Marshal.Sizeof(struct)
?