Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - ctypes: construct pointer from arbitrary integer

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...