Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Strange issue with LayoutKind.Explicit

$
0
0
Hello,

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;
    }


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


Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>