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

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

使用例

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

<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
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public int i;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public double d;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public char c;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public byte b;
}

フィールドが別の明示的に設定された場所で開始されるもう 1 つの例を次に示します。

 <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       
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public long lg;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public int i1;

    [System.Runtime.InteropServices.FieldOffset(4)]
    public int i2;

    [System.Runtime.InteropServices.FieldOffset(8)]
    public double d;

    [System.Runtime.InteropServices.FieldOffset(12)]
    public char c;

    [System.Runtime.InteropServices.FieldOffset(14)]
    public byte b;
}

i1 および i2 の各整数フィールドは、lg と同じメモリ位置を共有します。このような構造体レイアウトの制御は、プラットフォーム呼び出しのときに便利です。

参照

関連項目

リフレクション (C# および Visual Basic)

属性 (C# および Visual Basic)

カスタム属性の作成 (C# および Visual Basic)

リフレクションを使用した属性へのアクセス (C# および Visual Basic)

System.Reflection

Attribute

概念

C# プログラミング ガイド

その他の技術情報

Visual Basic のプログラミング ガイド

属性を使用したメタデータの拡張