ctypes:从任意整数构造指针 [英] ctypes: construct pointer from arbitrary integer
问题描述
出于低级目的,我需要从任意地址(以整数形式给出)构造ctypes指针。例如:
For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given as an integer. For instance:
INTP = ctypes.POINTER(ctypes.c_int)
p = INTP(0x12345678) # i *know* this is the address
但是所有此类尝试都会导致
But all such attempts result in
TypeError: expected c_long instead of int
有什么我可以克服的吗?如果有人想知道为什么我需要这样做,可以这样做是为了从 win32文件中提取
, OVERLAPPED
结构。PyOVERLAPPED
Is there anything I can do to overcome this? In case someone wonders why I need this, it's done so as to extract the OVERLAPPED
struct from a win32file.PyOVERLAPPED
, for integrating ctypes-exposed functions with win32file wrapped APIs.
谢谢,
-Tomer
Thanks,
-Tomer
推荐答案
您可以使用 ctypes.cast(addr,type)
。我将扩展您的示例以通过已知对象获取地址,以演示:
You can use ctypes.cast(addr, type)
. I'll extend your example to acquire an address via a known object, to demonstrate:
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
这篇关于ctypes:从任意整数构造指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!