Freigeben über


Vorgehensweise: Erstellen einer C/C++-Union mithilfe von Attributen (Visual Basic)

Mithilfe von Attributen können Sie anpassen, wie Strukturen im Arbeitsspeicher angeordnet werden. Zum Beispiel können Sie mithilfe der StructLayout(LayoutKind.Explicit)- und FieldOffset-Attribute eine sogenannte Union in C/C++ erstellen.

Beispiel 1

In diesem Codesegment beginnen alle Felder von TestUnion am gleichen Speicherort.

' 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

Beispiel 2

Im Folgenden sehen Sie ein weiteres Beispiel, bei dem Felder an unterschiedlichen explizit festgelegten Speicherorten beginnen.

' 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

Die beiden ganzzahligen Felder i1 und i2 teilen sich die gleichen Speicherorte wie lg. Diese Art der Kontrolle über das Strukturlayout ist nützlich, wenn Sie Plattformaufrufe nutzen.

Siehe auch