Procedura: Creare un'unione C/C++ tramite attributi (Visual Basic)

L'uso degli attributi consente di personalizzare la disposizione degli struct in memoria. Ad esempio, tramite gli attributi StructLayout(LayoutKind.Explicit) e FieldOffset è possibile creare una struttura che in C/C++ è nota come unione.

Esempio 1

In questo segmento di codice tutti i campi di TestUnion iniziano in corrispondenza della stessa posizione di memoria.

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

<System.Runtime.InteropServices.StructLayout(
      System.Runtime.InteropServices.LayoutKind.Explicit)>
Structure TestUnion
    <System.Runtime.InteropServices.FieldOffset(0)>
    Public i As Integer

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public d As Double

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public c As Char

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public b As Byte
End Structure

Esempio 2

Nell'esempio seguente i campi iniziano in corrispondenza di posizioni diverse impostate in modo esplicito.

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

 <System.Runtime.InteropServices.StructLayout(
      System.Runtime.InteropServices.LayoutKind.Explicit)>
Structure TestExplicit
     <System.Runtime.InteropServices.FieldOffset(0)>
     Public lg As Long

     <System.Runtime.InteropServices.FieldOffset(0)>
     Public i1 As Integer

     <System.Runtime.InteropServices.FieldOffset(4)>
     Public i2 As Integer

     <System.Runtime.InteropServices.FieldOffset(8)>
     Public d As Double

     <System.Runtime.InteropServices.FieldOffset(12)>
     Public c As Char

     <System.Runtime.InteropServices.FieldOffset(14)>
     Public b As Byte
 End Structure

I due campi integer, i1 e i2, condividono le stesse posizioni di memoria di lg. Questo tipo di controllo sul layout degli struct è utile quando si usa la chiamata di piattaforma.

Vedi anche