2010-07-04 78 views
0

我有以下代碼,當我運行它時,將1000字節傳遞給函數中的參數,結構MEMORY_BASIC_INFORMATION沒有使用任何變量,它們都保持爲0.我想知道這是否應該是?爲什麼這個結構的變量在被調用時沒有被填滿?

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

我在Core Duo 2.0Ghz上運行Vista Enterprise X64。

+0

http://www.pinvoke.net/default.aspx/kernel32.virtualquery – 2010-07-04 16:10:18

回答

1

那麼,使用uint來談論X64上的地址可能是一個問題。爲什麼-4096?

我剛纔想:

IntPtr currentAddr = new IntPtr(&stackInfo); 
+0

豈不一個'UINT在64位上也是64位的? – casablanca 2010-07-04 16:16:03

+0

卡薩布蘭卡:不; uint始終是System.UInt32類的包裝器。 – 2010-07-04 16:35:52

+0

@Warren - 特別是它總是一個*別名爲'System.UInt32'(不是一個包裝) – 2010-07-04 18:41:18

1

是的,這個代碼不能在64位操作系統上運行。演員陣容不對,MEMORY_BASIC_INFORMATION聲明也是錯誤的。這應該是更接近,未經檢驗的,因爲我現在無法接近到x64機器:

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

它沒有改變,仍然是結構變量是0 ... – 2010-07-04 16:52:03

+0

還有一個問題:dwLength參數聲明也是錯誤的,它是IntPtr。 – 2010-07-04 17:00:42

相關問題