在下面的代码我建立一个指针定位在任意存储位置的结构体:有效用途
[StructLayout(LayoutKind.Explicit)]
public struct S
{
[FieldOffset(0)] int f0;
[FieldOffset(4)] int f4;
public static void Main() {
unsafe {
S* rawPtr = (S*)0x1234;
rawPtr->f0 = 42;
}
}
}
如果更改f4
的类型object
代替我收到错误Compiler Error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('type')。
什么是struct S
的constaints允许建立这种类型的指针,在CIL
(而不仅仅是C#
)级别?
This page on MSDN说sbyte
,byte
,short
,ushort
,int
,uint
,long
,ulong
,char
,float
,double
,decimal
,bool
,枚举和指针是允许的,以及“用户定义的结构,它包含字段类型只有非托管类型“,但没有指定什么是非托管类型。
巧合的是,非托管类型是'sbyte','byte','short','ushort','int','uint','long','ulong','char','float','double ','decimal','bool',枚举和指针。 – 2013-03-25 09:53:33
@FrédéricHamidi我有点猜到了,但我想从官方文档或ECMA 335标准中明确说明。另外,我不确定结构是否应该有'StructLayout(LayoutKind.Explicit)'或类似的需求。 – 2013-03-25 10:29:42