Porady: tworzenie złożenia C/C++ za pomocą atrybutów (C# i Visual Basic)
Za pomocą atrybutów można dostosować sposób strukturach są układane w pamięci.Na przykład, można utworzyć, co jest znane Unii w c i C++ za pomocą StructLayout(LayoutKind.Explicit) i FieldOffset atrybuty.
Przykład
W tym segmencie kod, wszystkie pola z TestUnion start w tej samej lokalizacji w pamięci.
' 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
// Add a using directive for System.Runtime.InteropServices.
[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;
}
Poniżej przedstawiono inny przykład gdzie pola Rozpoczęcie w różnych jawnie ustawić lokalizacje.
' 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
// Add a using directive for System.Runtime.InteropServices.
[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;
}
Pola dwóch integer i1 i i2, udział w tej samej lokalizacji pamięci jako lg.Tego rodzaju kontroli nad układem struct jest przydatne podczas korzystania z wywołania platformy.
Zobacz też
Informacje
Tworzenie atrybutów niestandardowych (C# and Visual Basic)
Dostęp do atrybutów przy użyciu odbicia (C# i Visual Basic)
Koncepcje
Przewodnik programowania w języku C#