StructLayout and FieldOffset
The first of these attributes allows the programmer to control the physical layout of the fields in a ref class or value class. There are three possible orderings, Auto, Explicit, and Sequential, each of which is specified by an enumeration value of the same name, from the enumeration type LayoutKind. Auto layout results in the runtime's choosing an appropriate layout; this is the default. Explicit layout allows the programmer to dictate the precise position of each field by using a FieldOffset attribute. With sequential layout, the fields are laid out sequentially, in the order in which they are declared, with some suitable packing between adjacent fields. Here's an example of explicit layout control, and the output it produces:
using namespace System; using namespace System::Runtime::InteropServices; [StructLayout(LayoutKind::Explicit)] ref struct Overlap { [FieldOffset(0)] double d; [FieldOffset(0)] long long int lli; [FieldOffset(0)] int i0; [FieldOffset(4)] int i1; [FieldOffset(0)] unsigned char b0; [FieldOffset(1)] unsigned char b1; [FieldOffset(2)] unsigned char b2; [FieldOffset(3)] unsigned char b3; [FieldOffset(4)] unsigned char b4; [FieldOffset(5)] unsigned char b5; [FieldOffset(6)] unsigned char b6; [FieldOffset(7)] unsigned char b7; }; int main() { Overlap o; o.lli = o.i0 = o.i1 = 0; o.b0 = o.b1 = o.b2 = o.b2 = o.b3 = o.b4 = o.b5 = o.b6 = o.b7 = 0; o.d = 123.456E56; Console::WriteLine("d: {0}", o.d); Console::WriteLine("lli: {0:X16} ({1})", o.lli, o.lli); Console::WriteLine("i: {0:X8} {1:X8} ({2}, {3})", o.i1, o.i0, o.i1, o.i0); Console::WriteLine("b: {0:X2} {1:X2} {2:X2} {3:X2} {4:X2} " "{5:X2} {6:X2} {7:X2}", o.b7, o.b6, o.b5, o.b4, o.b3, o.b2, o.b1, o.b0); }
The output produced is:
d: 1.23456E+58 lli: 4BFF77E1401420EC (5476227481232220396) i: 4BFF77E1 401420EC (1275033569, 1075060972) b: 4B FF 77 E1 40 14 20 EC
The attribute StructLayout is applied to the type as a whole, while each of the fields that type contains has the attribute FieldOffset. In Visual C++, the field lli exactly overlays the double d, the pair of ints i0 and i1, and the eight byte fields b0–b7, resulting in a type having the characteristics of a Standard C++ union. This is confirmed by the output produced.
Consider the following layouts (see directory At05):
[StructLayout(LayoutKind::Explicit)] value struct SL1 { [FieldOffset(0)] int v; [FieldOffset(4)] unsigned char b; [FieldOffset(8)] int w; };
In this example, the layout is explicit, with the three fields having addresses 4 bytes apart.
[StructLayout(LayoutKind::Sequential, Pack = 4)] value struct SL2 { int v; unsigned char b; int w; };
In this example, the layout is sequential, there are no explicit offsets, and the packing factor is 4. This also results in the three fields having addresses 4 bytes apart.