6 out of 13 rated this helpful - Rate this topic

How to: Create a C/C++ Union Using Attributes (C# Programming Guide)

By using attributes you can customize how structs are laid out in memory. For example, you can create what is known as a union in C/C++ by using the StructLayout(LayoutKind.Explicit) and FieldOffset attributes.

Example

In this code segment, all of the fields of TestUnion start at the same location in memory.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public int i;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public double d;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public char c;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public byte b;
}

The following is another example where fields start at different explicitly set locations.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public long lg;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public int i1;

    [System.Runtime.InteropServices.FieldOffset(4)]
    public int i2;

    [System.Runtime.InteropServices.FieldOffset(8)]
    public double d;

    [System.Runtime.InteropServices.FieldOffset(12)]
    public char c;

    [System.Runtime.InteropServices.FieldOffset(14)]
    public byte b;
}

The two int fields, i1 and i2, share the same memory locations as lg. This sort of control over struct layout is useful when using platform invocation.

See Also

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
struct union sample

What is the C# equivalent of this code ;


typedef struct _CRYPT_KEY_SIGN_MESSAGE_PARA {
DWORD cbSize;
DWORD dwMsgAndCertEncodingType;
union {
HCRYPTPROV hCryptProv;
NCRYPT_KEY_HANDLE hNCryptKey;
} ;
DWORD dwKeySpec;
CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
void * pvHashAuxInfo;
CRYPT_ALGORITHM_IDENTIFIER PubKeyAlgorithm;
}CRYPT_KEY_SIGN_MESSAGE_PARA, *PCRYPT_KEY_SIGN_MESSAGE_PARA;

Advertisement