I am trying to marshal a struct
to a byte[]
and then back again but am getting an ArgumentOutOfRangeException
when marshaling back to struct
. Here is the code:
public struct Response
{
CommandNumber Command;
ushort EstimatedRoundTripDuration;
}
protected TStruct ByteArrayToStruct<TStruct>(byte[] data) where TStruct : struct
{
TStruct resp = new TStruct();
int size = Marshal.SizeOf(resp);
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(data, 0, ptr, size);
Marshal.PtrToStructure(ptr, resp);
return resp;
}
finally
{
Marshal.FreeHGlobal(ptr); //cleanup just in case
}
}
The problem seems to be that sizeof(Response)
is 3, whilst Marshal.SizeOf(resp)
is 4. I understand that these can be and are expected to be different but im using fairly basic types for this struct
. Can anyone shed any light on why the sizes are different?