次の方法で共有


C# で属性を使用して C/C++ の共用体を作成する方法

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

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

[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;
}

次のコードは、明示的に設定されたさまざまな場所でフィールドが開始される別の例です。

[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;
}

i1i2 を合わせた 2 つの整数フィールドは、lg と同じメモリ位置を共有します。 lg が最初の 8 バイトを使用するか、i1 が最初の 4 バイトを使用し、i2 は次の 4 バイトを使用します。 このような構造体配置の制御は、プラットフォームを呼び出すときに便利です。

関連項目