I've defined a struct for an externally defined data-packet as follows:
[StructLayout(LayoutKind.Explicit, Size=18, Pack=1, CharSet=CharSet.Ansi)]
struct FlexTransmission
{
[FieldOffset(0), MarshalAs(UnmanagedType.U4, SizeConst =4)]
public UInt32 transmissionTime;
[FieldOffset(4),MarshalAs(UnmanagedType.ByValArray, SizeConst = 13)]
public byte[] flexData; // size 13 bytes
[FieldOffset(17)]
public byte transmissionNumber;
}
However this structure is considered in error by the compiler (# 11, .NET 7):
System.TypeLoadException: 'Could not load type 'Flex.FlexTransmission' from assembly 'Flex, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.'
I can't see where the overlap could be. Surely an UInt32 doesn't take up more than 4 bytes in C# ?
Explicit layout is about how the data is stored in the managed space, and that has the demand that references must be aligned to the reference size. In reality, you simply shouldn't use explicit layout for anything containing a reference - and the array here: is a reference.
I wonder if instead of using a byte[]
, you should have used a fixed buffer; that doesn't have this restriction:
public unsafe fixed byte flexData[13];