Partager via


Guide pratique pour créer une union C/C++ à l’aide d’attributs (Visual Basic)

En utilisant des attributs, vous pouvez personnaliser la façon dont les structs sont disposés en mémoire. Par exemple, vous pouvez créer ce qu’on appelle une union en C/C++ à l’aide des attributs StructLayout(LayoutKind.Explicit) et FieldOffset.

Exemple 1

Dans ce segment de code, tous les champs de TestUnion début au même emplacement en mémoire.

' 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

Exemple 2

Voici un autre exemple où les champs commencent à différents emplacements définis explicitement.

' 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

Les deux champs entiers, i1 et i2, partagent les mêmes emplacements de mémoire que lg. Ce type de contrôle sur la disposition de struct est utile lors de l’utilisation d’un appel de plateforme.

Voir aussi