ctypes:从任意整数构造指针

27

我需要进行低级别操作,需要从一个以整数形式给出的任意地址构建ctypes指针。例如:

INTP = ctypes.POINTER(ctypes.c_int)
p = INTP(0x12345678) # i *know* this is the address

但是所有这样的尝试都导致

TypeError: expected c_long instead of int

是否有什么方法可以克服这个问题?以防有人想知道我为什么需要这样做,它是为了从win32file.PyOVERLAPPED中提取OVERLAPPED结构体,用于将ctypes公开的函数与win32file包装的API集成。

谢谢,
-Tomer

1个回答

41
你可以使用 ctypes.cast(addr, type)。我��扩展你的示例以通过已知对象获取地址,以演示:
INTP = ctypes.POINTER(ctypes.c_int)
num = ctypes.c_int(42)
addr = ctypes.addressof(num)
print 'address:', addr, type(addr)
ptr = ctypes.cast(addr, INTP)
print 'pointer:', ptr
print 'value:', ptr[0]

输出:

address: 4301122528 <type 'int'>
pointer: <__main__.LP_c_int object at 0x1005decb0>
value: 42

1
@sebulba:如果可以的话,请将答案标记为正确。:) - vines
那么 print('value:', ptr.contents) 呢? - Haseeb Mir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接