Bagikan melalui


Panduan untuk Membuat Union C/C++ dengan Menggunakan Atribut dalam Visual Basic

Dengan menggunakan atribut, Anda dapat menyesuaikan bagaimana struktur ditata dalam memori. Misalnya, Anda dapat membuat apa yang dikenal sebagai union di C/C++ dengan menggunakan atribut StructLayout(LayoutKind.Explicit) dan FieldOffset.

Contoh 1

Dalam segmen kode ini, semua bidang TestUnion mulai di lokasi yang sama dalam memori.

' 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

Contoh 2

Berikut adalah contoh lain di mana bidang dimulai di lokasi berbeda yang ditetapkan secara eksplisit.

' 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

Dua bidang bilangan bulat, i1 dan i2, berbagi lokasi memori yang sama dengan lg. Kontrol semacam ini atas tata letak struktur berguna saat menggunakan pemanggilan platform.

Lihat juga