我有以下 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/