C++ vs Python | Read Memory

Question:

Have working code in C++ and would like to get equivalent results with Python.
The idea is to retrieve data from memory using a specific process and a pointer. The result should look like this as it works in C++:
C++ results
Here is the C++ code:

hProcess = SOME_HANDLER
addr = SOME_POINTER
SIZE_T bytesRead = 0;
SIZE_T sizeBuff = 0x4000;
BYTE buff[sizeBuff];

ReadProcessMemory(hProcess, addr, buff, sizeBuff, &bytesRead);

In Python I have tried this:

read_buffer = (ctypes.c_char * 0x4000)()
lp_buffer = ctypes.byref(read_buffer)
n_size = ctypes.sizeof(read_buffer)
lp_number_of_bytes_read = ctypes.c_ulong(0)
ctypes.windll.kernel32.ReadProcessMemory(self.handle, ctypes.c_void_p(lp_base_address), lp_buffer, n_size, lp_number_of_bytes_read)
result = read_buffer.value

Which gave me this result:

`b'hAxdfx01<Bxdfx01xb9txbat'` 

I don’t know what this means or if it contains anything useful.

Asked By: elector

||

Answers:

result is a value of type bytes, which represents a series of integer values between 0 and 255, inclusive.

When you display the each byte is show in one of two forms:

  1. If the byte corresponds to a printable ASCII character, it is shown as that character.
  2. Otherwise, it is shown as a hexadecimal integer prefixed with x.

Iterating over a bytes value yields a sequence of int objects:

>>> list(result)
[104, 65, 223, 1, 60, 66, 223, 1, 185, 9, 186, 9]

(Note that ord('h') == 104, ord('A') == 65, xdf == 223, etc.)

As mentioned in the comments, the struct package can be used to extract "usable" objects from a raw bytes value. For example, one could treat these 12 bytes as 3 unsigned 4-byte words in big-endian byte order:

>>> import struct
>>> struct.unpack(">III", result)
(1749147393, 1011015425, 3104422409)

or 6 unsigned 2-byte words in little-endian byte order:

>>> struct.unpack("<HHHHHH", result)
(16744, 479, 16956, 479, 2489, 2490)
Answered By: chepner
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.