Sdílet prostřednictvím


Jak: vytvoření unie C/C++ pomocí atributů (C# a Visual Basic)

Pomocí atributů lze upravit, jak jsou rozloženy struktur v paměti.Můžete například vytvořit známým jako unie v C/C++ pomocí StructLayout(LayoutKind.Explicit) a FieldOffset atributy.

Příklad

Tento kód segmentu, všechna pole z TestUnion start ve stejném umístění v paměti.

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

Je jiný příklad kde začít polí na různých explicitně nastavit umístění.

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

Dvou celočíselných polí i1 a i2, sdílet stejné umístění paměti jako lg.Toto řazení řídit rozložení struktura je užitečné při použití platformy vyvolání.

Viz také

Referenční dokumentace

Odraz (C# a Visual Basic)

Atributy (C# a Visual Basic)

Vytvoření vlastní atributy (C# a Visual Basic)

Přístup atributy pomocí odrazu (C# a Visual Basic)

System.Reflection

Attribute

Koncepty

Příručka programování C#

Další zdroje

Příručka programování v jazyce Visual Basic

Rozšíření metadat pomocí atributů