user1166981
user1166981

Reputation: 1746

Most efficient method to readprocessmemory for neighbouring addresses?

I am reading addresses in memory with the below code. It occurred to me that I may be doing this very inefficiently as I am making individual calls for every address despite all of the addresses being neighbours to each other (1 byte along).

    [DllImport("kernel32", EntryPoint = "ReadProcessMemory")]
    private static extern byte ReadProcessMemoryByte(int Handle, int Address, ref byte Value, int Size, ref int BytesRead);

The function looks something like:

pseudo: 
       For loop: 
       read memory address (base address offset)
       add result to array
       addressoffset++

So say I have 3 addresses, I would be making 3 separate calls. Is there a way to make just 1 call and then do so internal logic to split the result into 3 separate data segments, if you know what I mean? Like instead of reading byte by byte, read 4 bytes at once then split them up before adding to the array?

The reason I am asking this is that my program takes forever to go through the iterations, sometimes having to read up to 40,000 addresses which takes 3 minutes. If I could do what I am asking, then maybe I could cut it down under a minute?

Upvotes: 0

Views: 908

Answers (1)

Tim S.
Tim S.

Reputation: 56536

From http://www.pinvoke.net/default.aspx/kernel32.readprocessmemory, the method signature should be like:

  [DllImport("kernel32.dll", SetLastError = true)]
  static extern bool ReadProcessMemory( 
    IntPtr hProcess, 
    IntPtr lpBaseAddress,
    [Out] byte[] lpBuffer, 
    int dwSize, 
    out int lpNumberOfBytesRead
   );

Currently, since you only have a single byte for lpBuffer/Value, you are only reading one byte at a time. You can read many more (maybe all of the bytes you intend to read, or broken up into, say, 1024 byte chunks) by making that a byte[] and passing a Size larger than 1.

Upvotes: 2

Related Questions