Condividi tramite


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

Usando gli attributi è possibile personalizzare la disposizione degli struct in memoria. Ad esempio, è possibile creare ciò che è noto come unione in C/C++ usando gli StructLayout(LayoutKind.Explicit) attributi e FieldOffset .

Esempio 1

In questo segmento di codice tutti i campi di TestUnion iniziano nella stessa posizione in 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

Di seguito è riportato un altro esempio in cui i campi iniziano in 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 interi, 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 alla piattaforma.

Vedere anche