ctypes: 从任意整数构造指针

27 投票
1 回答
13847 浏览
提问于 2025-04-16 16:24

为了低级别的目的,我需要从一个任意的地址(以整数形式给出)构造一个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

撰写回答