次の方法で共有


方法: 属性を使用して C/C++ 共用体を作成する (Visual Basic)

属性を使用すると、構造体をメモリ内に配置する方法をカスタマイズできます。 たとえば、 StructLayout(LayoutKind.Explicit) 属性と FieldOffset 属性を使用して、C/C++ で共用体と呼ばれるものを作成できます。

例 1

このコード セグメントでは、 TestUnion のすべてのフィールドがメモリ内の同じ場所から開始されます。

' 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

例 2

次に示すもう 1 つの例では、フィールドが異なる明示的に設定された場所から始まります。

' 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

i1i2の 2 つの整数フィールドは、lgと同じメモリ位置を共有します。 この種の構造体レイアウトの制御は、プラットフォーム呼び出しを使用する場合に便利です。

こちらも参照ください