.NET Framework Platform Invoke Marshaling unions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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); } }
}


Got any .NET Framework Question?