Marshaling unions

suggest change

Value-type fields only

C++ declaration

typedef union
{
    char c;
    int i;
} CharOrInt;

C# declaration

[StructLayout(LayoutKind.Explicit)]
public struct CharOrInt
{
    [FieldOffset(0)]
    public byte c;
    [FieldOffset(0)]
    public int i;
}

Mixing value-type and reference fields

Overlapping a reference-type field with a value-type field is not allowed, so putting FieldOffset(0) on both a byte[] text and an int i will not compile for

typedef union
{
    char text[128];
    int i;
} TextOrInt;

In general that layout needs custom marshaling. In a case like this, a simpler technique works: the int is not a separate field, and the property reads the first four bytes of the array:

[StructLayout(LayoutKind.Sequential)]
public struct TextOrInt
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
    public byte[] text;
    public int i { get { return BitConverter.ToInt32(text, 0); } }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents