Aracılığıyla paylaş


Nasıl yapılır: Öznitelikleri Kullanarak C/C++ Birleşimi Oluşturma (Visual Basic)

Öznitelikleri kullanarak yapıların bellekte nasıl yerleştirileceği özelleştirebilirsiniz. Örneğin, C/C++ dilinde birleşim olarak bilinen bir yapıyı, StructLayout(LayoutKind.Explicit) ve FieldOffset özniteliklerini kullanarak oluşturabilirsiniz.

Örnek 1

Bu kod parçasında, TestUnion'nin tüm alanları bellekte aynı konumda başlar.

' 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

Örnek 2

Aşağıda, alanların açıkça ayarlanmış farklı konumlarda başladığı başka bir örnek verilmiştir.

' 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

i1 ve i2 ile iki tamsayı alanı, lg ile aynı bellek konumlarını paylaşır. Yapı düzeni üzerinde bu tür bir denetim, platform çağrısı kullanılırken kullanışlıdır.

Ayrıca bakınız