2013-03-25 28 views
3

在下面的代码我建立一个指针定位在任意存储位置的结构体:有效用途

[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 MSDNsbytebyteshortushortintuintlongulongcharfloatdoubledecimalbool,枚举和指针是允许的,以及“用户定义的结构,它包含字段类型只有非托管类型“,但没有指定什么是非托管类型。

+1

巧合的是,非托管类型是'sbyte','byte','short','ushort','int','uint','long','ulong','char','float','double ','decimal','bool',枚举和指针。 – 2013-03-25 09:53:33

+0

@FrédéricHamidi我有点猜到了,但我想从官方文档或ECMA 335标准中明确说明。另外,我不确定结构是否应该有'StructLayout(LayoutKind.Explicit)'或类似的需求。 – 2013-03-25 10:29:42

回答

2

我不能在网上找到ECMA-335易于浏览的版本,但ECMA-334 paragraph 27.2说:

非托管型是任何类型的不是引用类型,一个 类型参数或通用结构类型并且不包含 类型不是非托管类型的字段。换句话说,一个非托管型是下列 之一:

  • sbytebyteshortushortintuintlongulongcharfloatdoubledecimal,或bool

  • 任何枚举型

  • 任何指针型

  • 任何非通用的用户定义的包含非托管类型只的字段结构类型

[:构造类型和类型参数从来 非托管类型注完]

结构的包装方式似乎并没有被相关与这个区别。