2012-04-01 114 views
0

我有代碼從內存中讀取一個值,當內存地址指向一個靜態的4字節值時,但我試圖訪問一個4字節的值在動態位置,因此需要先搜索指針,然後再次搜索以獲取4字節值。C#ReadProcessMemory - 訪問/讀指針

下面是我應該返回指針的地址,但它只是輸出0的代碼...

bAddr = (IntPtr)0x0017C370; // Base address to find the Pointer (Currently: 0x00267A50) 
ReadProcessMemory(hProc, bAddr, buffer, 4, out bytesRW); 
output = BitConverter.ToInt32(buffer, 0); 
txtOutput.Text = output.ToString(); 

我看工作作爲僞代碼:

bAddr = (IntPtr)0x0017C370; // Base address to find the Pointer (Currently: 0x00267A50) 
ReadProcessMemory(hProc, bAddr, buffer, 4, out bytesRW); 
output = BitConverter.ToInt32(buffer, 0); 
bAddr = (IntPtr)output; // Should now contain the address 0x00267A50 
ReadProcessMemory(hProc, bAddr, buffer, 4, out bytesRW); 
output = BitConverter.ToInt32(buffer, 0); 
txtOutput.Text = output.ToString(); 

任何人都可以擺脫任何關於我需要做的事情來找到一個地址,然後搜索該地址找到一個值?

+0

ReadProcessMemory返回什麼?它可能只是失敗,在這種情況下'GetLastError'可能會有一些亮點。 – 2012-04-01 17:38:27

回答

4

這是使用pinvoke執行Win32函數時的一個非常經典的錯誤,您沒有執行任何錯誤檢查。所以任何失敗都是不可想象的。首先確保你宣佈它正確:

[DllImport("user32.dll", SetLastError = true)] 
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, 
    [In, Out] byte[] buffer, IntPtr size, out IntPtr lpNumberOfBytesRead); 

這樣然後執行它:

bool ok = ReadProcessMemory(...); 
if (!ok) throw new System.ComponentModel.Win32Exception(); 

現在,你知道爲什麼它不工作。除非您至少以這種方式進行測試,否則我們無法幫助您找出問題所在。最基本的問題是猜測地址錯誤當然。由於顯而易見的原因,ReadProcessMemory不具有足夠的權限,因此它是一種非常有特權的功能。

+0

這個。始終總是總是從p/invoke調用中檢查你的結果 - 如果你不想錯誤地拋出*,只需創建一個新的Win32Exception(),併爲你填充所有的錯誤細節。 – JerKimball 2012-12-26 16:33:17