我正在玩ctypes
和ReadProcessMemory
。
我希望能够读取一块内存并将其转换为 ctypes 类型,然后访问正确的值。
目前,当取消引用指针时,这会失败。这是一个最小的例子:
# a minimal example
from ctypes import *
import win32api
class Test(Structure):
_fields_ = [
('p', POINTER(c_int)),
('pp', POINTER(POINTER(c_int)))
]
rpm = windll.kernel32.ReadProcessMemory
PROCESS_ALL_ACCESS = 0x1F0FFF
pid = 10520
addr = 0x409E4260
process = win32api.OpenProcess(PROCESS_ALL_ACCESS, 0, pid)
size = sizeof(Test)
buff = create_string_buffer(size)
bytes_read = c_size_t()
success = rpm(
process.handle,
addr, # where to read from
buff, # output
size, # how much to read
byref(bytes_read)
)
if not success:
print " Error reading memory: " + str(get_last_error())
else:
test = cast(buff, POINTER(Test)).contents
print test
# access pointers
print test.p
print test.pp
# dereference pointers
print test.p.contents
print test.pp.contents
最后两行使python崩溃,我认为是因为它试图访问另一个进程的内存。(?)
我编写了一个递归函数,可以通过重复调用 ReadProcessMemory 来取消引用指针,但是这对于复杂的结构来说很笨重。
我究竟做错了什么?最好的方法是什么?