在下面的代码中,我构建了一个指向位于任意内存位置的结构的指针:
[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
而不是 int
,我会收到错误 Compiler Error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('type') .
struct S
上允许在 CIL
(而不仅仅是 C#
)级别在该类型上构建指针的约束是什么?
This page on MSDN说 sbyte
, byte
, short
, ushort
, int
, uint
, long
, ulong
, char
, float
, double
,允许使用 decimal
、bool
、枚举和指针,以及“仅包含非托管类型字段的用户定义结构类型”,但未指定非托管类型类型是。
最佳答案
我无法在网上找到易于导航的 ECMA-335 版本,但是 ECMA-334 paragraph 27.2说:
An unmanaged-type is any type that isn’t a reference-type, a type-parameter, or a generic struct-type and contains no fields whose type is not an unmanaged-type. In other words, an unmanaged-type is one of the following:
sbyte
,byte
,short
,ushort
,int
,uint
,long
,ulong
,char
,float
,double
,decimal
, orbool
.Any enum-type.
Any pointer-type.
Any non-generic user-defined struct-type that contains fields of unmanaged-types only.
[Note: Constructed types and type-parameters are never unmanaged-types. end note]
结构的打包模式似乎与这种区别无关。
关于c# - 在 C# 中有效使用指向任意内存位置的原始指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15611778/