c# - 使用指针和地址

标签 c#

我有以下 C# 代码: (更新代码/问题) 代码和项目被标记为不安全

private struct MEMORY_BASIC_INFORMATION
        {
            internal uint BaseAddress;
            internal uint AllocationBase;
            internal uint AllocationProtect;
            internal uint RegionSize;
            internal uint State;
            internal uint Protect;
            internal uint Type;
        }


public unsafe static bool CheckForSufficientStack(long bytes)
{
    MEMORY_BASIC_INFORMATION stackInfo = new MEMORY_BASIC_INFORMATION();

    // originally was
    // IntPtr currentAddr = new IntPtr((uint)&stackInfo - 4096);

    GCHandle gh = GCHandle.Alloc(stackInfo, GCHandleType.Pinned);
    IntPtr p = gh.AddrOfPinnedObject();

    //now - this line passes compilation        
    IntPtr currentAddr = new IntPtr((uint)p - 4096);

    // build error in the below line
    VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));

   return ((uint)currentAddr.ToInt64() - stackInfo.AllocationBase) >
                   (bytes + STACK_RESERVED_SPACE);
}

当我编译它时,我收到错误: 无法获取托管类型的地址、获取其大小或声明指向托管类型的指针

这是我复制的代码,我实际上很惊讶地知道 C# 中有“&”,但构建失败了。

知道如何解决这个问题吗?

当我们执行 sizeof(MEMORY_BASIC_INFORMATION) 时,错误出现在最后一行

最佳答案

您必须首先将对象“固定”在内存中,以确保 GC 在您使用它时不会移动它:

GCHandle gh = GCHandle.Alloc(stackInfo, GCHandleType.Pinned);
IntPtr p = gh.AddrOfPinnedObject();

获取结构体的大小:

Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))

关于c# - 使用指针和地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39952205/

相关文章:

c# - MeasureString 忽略 Arial 和 Times New Roman 的字体样式

c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏

python - 错误ArgumentException : JSON must represent an object type from PyZeroMQ server

c# - 在内存中模拟 LinqToSql 存储库以用于单元测试

c# - 在 C# 中创建一个批处理文件

c# - 十进制的自定义格式#

c# - 如何在具有一个不同值的列表中查找相同的类

c# - 使用 SqlKata 执行多个查询

c# - 以编程方式创建 ASPX 页面的实例并解析 html

c# - 复杂的 C# Linq 算法