Sunday, October 26, 2008

Implementing "C/C++" [union] in .Net

To improve performance, the CLR is capable of arranging the fields of a type any way it chooses. When you define a type, you can tell the CLR whether it must keep the type's fields in the same order as the developer specified them or whether it can reorder them as it sees fit.
The System.Runtime.InteropServices.StructLayoutAttribute attribute is used to tell the CLR what to do (how to layout the fields). You can pass LayoutKind.Auto as a value to the above specified attribute to have the CLR arrange the fields, or LayoutKind.Sequential, to have the CLR preserve the given layout, or LayoutKind.Explicit, to explicitly arrange the fields in memory by using offsets.
Microsoft's C# compiler selects LayoutKind.Auto for reference types, and LayoutKind.Sequential for value types.
As was mentioned above, the StructLayoutAttribute also allows you to explicitly indicate the offset of each field by passin LayoutKind.Explicit to its constructor. Then you apply an instance of the System.Runtime.InteropServices.FieldOffsetAttribute attribute to each field passing to this attribute's constructor an Int32, indicating the offset of the field's first byte from the beginning of the instance in bytes. Here is an example:

public struct CUnionAlternate
byte byteField;
short shortField;

No comments: