通过使用属性,可以自定义结构在内存中的布局方式。 例如,可以使用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
下面是另一个示例,其中字段以不同的显式设置位置开始。
' 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
两个整数字段 i1
和 i2
与 lg
共享相同的内存位置。 使用平台调用时,这种对结构布局的控制非常有用。