windows - Monitoring memory addresses in Python -
i need know how monitor memory address , values in python. example: have game written in c. want write python script read memory address of current hitpoints , take actions based on values.
i can memory addresses cheatengine, don't know how use in python.
here's read_process
function. result either bytes
(2.x str
), or array of ctypes structures. default read 1 byte process. optional dtype
parameter must ctypes type, such ctypes.c_cint
or ctypes.structure
subclass. reads array of given type , length
.
be careful avoid dereferencing pointer values. example, if pass dtype=c_char_p
, indexing result array try dereference remote pointer in current process, crash python. in previous answer wrote read-only remotepointer
class if need handle case.
ctypes definitions
import ctypes ctypes import wintypes kernel32 = ctypes.windll('kernel32', use_last_error=true) process_vm_read = 0x0010 size_t = ctypes.c_size_t psize_t = ctypes.pointer(size_t) def _check_bool(result, func, args): if not result: raise ctypes.winerror(error) return args kernel32.openprocess.errcheck = _check_bool kernel32.openprocess.restype = wintypes.handle kernel32.openprocess.argtypes = ( wintypes.dword, # _in_ dwdesiredaccess wintypes.bool, # _in_ binherithandle wintypes.dword) # _in_ dwprocessid kernel32.closehandle.errcheck = _check_bool kernel32.closehandle.argtypes = ( wintypes.handle,) kernel32.readprocessmemory.errcheck = _check_bool kernel32.readprocessmemory.argtypes = ( wintypes.handle, # _in_ hprocess wintypes.lpcvoid, # _in_ lpbaseaddress wintypes.lpvoid, # _out_ lpbuffer size_t, # _in_ nsize psize_t) # _out_ lpnumberofbytesread
read_process
definition
def read_process(pid, address, length=1, dtype=ctypes.c_char): result = (dtype * length)() nread = size_t() hprocess = kernel32.openprocess(process_vm_read, false, pid) try: kernel32.readprocessmemory(hprocess, address, result, ctypes.sizeof(result), ctypes.byref(nread)) finally: kernel32.closehandle(hprocess) if issubclass(dtype, ctypes.c_char): return result.raw return result
example
if __name__ == '__main__': import os class dtype(ctypes.structure): _fields_ = (('x', ctypes.c_int), ('y', ctypes.c_double)) source = (dtype * 2)(*[(42, 3.14), (84, 2.72)]) pid = os.getpid() address = ctypes.addressof(source) sink = read_process(pid, address, 2, dtype) din, dout in zip(source, sink): assert din.x == dout.x assert din.y == dout.y size = ctypes.sizeof(source) buf_source = ctypes.string_at(source, size) buf_sink = read_process(pid, address, size) assert buf_source == buf_sink
Comments
Post a Comment