Edit

How to: Create a C/C++ Union by Using Attributes (Visual Basic)

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 1

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

' Add an Imports statement for System.Runtime.InteropServices.


Structure TestUnion
    
    Public i As Integer

    
    Public d As Double

    
    Public c As Char

    
    Public b As Byte
End Structure

Example 2

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

' Add an Imports statement for System.Runtime.InteropServices.

 
Structure TestExplicit
     
     Public lg As Long

     
     Public i1 As Integer

     
     Public i2 As Integer

     
     Public d As Double

     
     Public c As Char

     
     Public b As Byte
 End Structure

The two integer 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