c# - 在 C# 中有效使用指向任意内存位置的原始指针

标签 c# pointers unmanaged unmanaged-memory

在下面的代码中,我构建了一个指向位于任意内存位置的结构的指针:

[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 MSDNsbyte, byte, short, ushort, int, uint , long, ulong, char, float, double,允许使用 decimalbool、枚举和指针,以及“仅包含非托管类型字段的用户定义结构类型”,但未指定非托管类型类型是。

最佳答案

我无法在网上找到易于导航的 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, or bool.

  • 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/

相关文章:

c - (*b)[0] 与 *b[0] - 数组和指针

c# - C# 中的非托管 C++ 类

.net - 什么 .NET UnmanagedType 是 Unicode (UTF-16)?

c# - FindNextPrinterChangeNotification 错过事件?

c# - C# 中的文件系统观察程序仅被触发一次

c# - 更改 .NET Framework 时 Visual Studio 中的数据库连接丢失

c# - 如何测试包含 Application.Current 的方法

c - 为什么将 double ** 分配给 void ** 是一个警告?

C 段错误 : 11 error

c# - 如何将 PCL 转换为基于 .net 标准的库