Delen via


Procedure: Een C/C++-samenvoeging maken met behulp van kenmerken (Visual Basic)

Met behulp van kenmerken kunt u aanpassen hoe structs in het geheugen worden ingedeeld. U kunt bijvoorbeeld een samenvoeging maken in C/C++ met behulp van de StructLayout(LayoutKind.Explicit) en FieldOffset kenmerken.

Voorbeeld 1

In dit codesegment beginnen alle velden op TestUnion dezelfde locatie in het geheugen.

' 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

Voorbeeld 2

Hier volgt een ander voorbeeld waarin velden op verschillende expliciet ingestelde locaties 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

De twee gehele getallen en i1i2delen dezelfde geheugenlocaties als lg. Dit soort controle over de structindeling is handig bij het gebruik van platformoproep.

Zie ook