【发布时间】:2013-03-25 09:43:32
【问题描述】:
在以下代码中,我构建了一个指向位于任意内存位置的结构的指针:
[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, char, @986 、decimal、bool、枚举和指针是允许的,以及“用户定义的仅包含非托管类型字段的结构类型”,但没有指定非托管类型是什么。
【问题讨论】:
-
巧合的是,非托管类型有
sbyte、byte、short、ushort、int、uint、long、char、@98764 987654352@、double、decimal、bool、枚举和指针。 -
@FrédéricHamidi 我有点猜到了,但我想从官方文档或 ECMA 335 标准中得到明确的声明。另外,我不确定该结构是否应该有
StructLayout(LayoutKind.Explicit)或类似的要求。
标签: c# pointers unmanaged unmanaged-memory