开发者

why are the variables of this structure not filled up when called?

I have the following code and when I run it, passing 1000 bytes to the parameter in the function, the structure MEMORY_BASIC_INFORMATION has none of its variables used, they开发者_开发技巧 all stay the value 0. I wondered if that is supposed to be?

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

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

  VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));

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

private const long STACK_RESERVED_SPACE = 4096 * 16;

[DllImport("kernel32.dll")]
private static extern int VirtualQuery(
  IntPtr lpAddress,
  ref MEMORY_BASIC_INFORMATION lpBuffer,
  int dwLength);

   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;
    }

I'm running a Vista Enterprise X64 on a Core Duo 2.0Ghz.


Well, using uint to talk about an address on X64 could be a problem. And why the -4096?

I'd have thought just:

IntPtr currentAddr = new IntPtr(&stackInfo);


Yes, this code cannot work on a 64-bit operating system. The casts are wrong, so is the declaration of the MEMORY_BASIC_INFORMATION. This ought to be closer, untested since I'm not close to an x64 machine right now:

    public unsafe static bool CheckForSufficientStack(long bytes) {
        var stackInfo = new MEMORY_BASIC_INFORMATION();
        IntPtr currentAddr = new IntPtr((long)&stackInfo - 4096);
        VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));
        return (currentAddr.ToInt64() - (long)stackInfo.AllocationBase) > (bytes + STACK_RESERVED_SPACE);
    }

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜