开发者

ctypes: construct pointer from arbitrary integer

开发者 https://www.devze.com 2023-02-28 10:54 出处:网络
For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given开发者_如何学编程 as an integer. For instance:

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

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.

Thanks,

-Tomer


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]

Output:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号