Type Summary



Type Summary


CF public sealed class FieldOffsetAttribute : Attribute

       {

       // Constructors

       CF public FieldOffsetAttribute(int offset);



       // Properties

       CF public int Value { get; }

       }


AN: The most common use of FieldOffsetAttribute is to create a union. But whenever you use FieldOffsetAttribute, make sure that you avoid burning in platform-specific memory offsets. This isn't easy, since you can't get around specifying the absolute offsets at compile time, but you can create substructures to restrict the number of fields whose offsets need to be specified. This is demonstrated by the following C# definitions for a structure containing a union that follows a pointer-sized field:


// This definition is bad because it's only correct when

// the size of a pointer is 32-bits.

[StructLayout(LayoutKind.Explicit)]

struct Bad

{

    [FieldOffset(0)] public IntPtr pointerSizedField;

    [FieldOffset(4)] public short unionField1;

    [FieldOffset(4)] public double unionField2;

}

// This definition is good because it leverages sequential

// layout to handle the structure's varying size, and only

// uses explicit layout where absolutely necessary.

[StructLayout(LayoutKind.Sequential)]

struct Good

{

    public IntPtr pointerSizedField;

    public GoodUnion union;

}



[StructLayout(LayoutKind.Explicit)]

struct GoodUnion

{

    [FieldOffset(0)] public short unionField1;

    [FieldOffset(0)] public double unionField2;

}


Having to create the substructures is a bit of a pain, but in the absence of being able to give sizeof(IntPtr) as a field offset or mixing sequential and explicit layout in the same structure, this is the way to do it.