Sheen Space

C# Notes: Class Layout – explicitlayout

leave a comment »


Description in CLI specification:

explicitlayout: A class marked explicitlayout causes the loader to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets and/or overall class size or alignment.

This is usually used to define exact class bit layout, to communicate with unmanaged code, like C/C++ code, which requires accurate class layout and / or alignment; or to send over network, in specific packet format, like TCP/IP.

Usage:

[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
public class MySystemTime
{
    [FieldOffset(0)]public ushort wYear;
    [FieldOffset(2)]public ushort wMonth;
    [FieldOffset(4)]public ushort wDayOfWeek;
    [FieldOffset(6)]public ushort wDay;
    [FieldOffset(8)]public ushort wHour;
    [FieldOffset(10)]public ushort wMinute;
    [FieldOffset(12)]public ushort wSecond;
    [FieldOffset(14)]public ushort wMilliseconds;
}

Note that, when FieldOffset is used, it takes precedence over Pack and Size specified in StructLayout attribute.

Advertisements

Written by Ying

19/09/2010 at 01:24

Posted in Programming, Technology

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: