解除引用外部ctypes指针时Python崩溃

时间:2013-04-04 22:23:16

标签: python windows ctypes

我在Windows中玩ctypesReadProcessMemory

我希望能够读取一大块内存并将其转换为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来取消引用指针,但是这对于复杂的结构很笨拙。

我做错了什么?最好的方法是什么?

0 个答案:

没有答案