Marshalling unions in .NET

csharp

A simple union in c might look as the one below:


union simpleUnion
{
	char a[10];
	int b;
}

The memory allocation would require sizeof(char) * 10 bytes (since it is the biggest element in that union).

Our task is to marshal this type into unmanaged environment:
We need to control the memory position of each member of a .NET struct,
and the way to do this will be to apply the StructLayout attribute 

StructLayoutAttribute(LayoutKind.Explicit)]
internal struct simpleUnion
{
    [FieldOffsetAttribute(0)]
    public char[] a;
    [FieldOffsetAttribute(0)]
    public int b;
}

Post a Comment

Previous Post Next Post