David Kuske
David Kuske

Reputation: 11

C# ReadProcessMemory - Accessing/Reading Pointers

I have the code to read a value from Memory which works when the memory address points to a static 4 byte value, but i'm trying to access a 4 byte value which is in a dynamic location and so need to search for the pointer first then search again to get the 4 byte value.

Below is the code I have which should return the address of the Pointer but it just outputs 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();

Pseudo code I see working as:

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();

Can anyone shed any light on to what I need to be doing to find an address and then search for that address to find a value?

Upvotes: 0

Views: 2613

Answers (1)

Hans Passant
Hans Passant

Reputation: 941485

This is a pretty classical mistake when using pinvoke to execute Win32 functions, you are not doing any error checking. So any failure is undiagnosable. First make sure you declared it properly:

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

Then execute it like this:

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

Now you'll know why it doesn't work. We can't otherwise help you figure out what goes wrong until you've at least tested it this way. The most basic problem is guessing the address wrong of course. And not having enough privileges, ReadProcessMemory is a highly privileged function for obvious reasons.

Upvotes: 4

Related Questions