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 value with a value type one is not allowed so you cannot simply use the FieldOffset(0) text; FieldOffset(0) i; will not compile for

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

and generally you would have to employ custom marshaling. However, in particular cases like this simpler technics may be used:

[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