Hello,
I created an explicit structure as below:
IMHO, this should work perfectly.
But when I use the above structure, I get type load exception saying "because it contains an object field at offset 2 that is incorrectly aligned or overlapped by a non-object field."
I tried many things and finally came up with the below structure:
and now it works fine.
My question is: Why do I need to start my byte array from offset '4', when a short type takes only 2 bytes. So what happens to the next two bytes (byte 3 and byte 4) after the short?
Regards,
Jayanta
I created an explicit structure as below:
Code Snippet: Version A
[StructLayout(LayoutKind.Explicit)]
public struct ExplicitStruct
{
[FieldOffset(0)]
public short mShort;
[FieldOffset(2)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public byte[] mByteArray;
[FieldOffset(8)]
public long mLong;
}
IMHO, this should work perfectly.
But when I use the above structure, I get type load exception saying "because it contains an object field at offset 2 that is incorrectly aligned or overlapped by a non-object field."
I tried many things and finally came up with the below structure:
Code Snippet: Version B
[StructLayout(LayoutKind.Explicit)]
public struct ExplicitStruct
{
[FieldOffset(0)]
public short mShort;
//notice the change in offset
[FieldOffset(4)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public byte[] mByteArray;
[FieldOffset(10)]
public long mLong;
}
My question is: Why do I need to start my byte array from offset '4', when a short type takes only 2 bytes. So what happens to the next two bytes (byte 3 and byte 4) after the short?
Regards,
Jayanta