2011-04-25 131 views
20

對於低級別目的,我需要從任意地址構造一個ctypes指針,以整數形式給出。例如: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

回答

31

您可以使用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 
+0

,做的伎倆,謝謝! – sebulba 2011-04-26 08:34:31

+1

@sebulba:如果有,請將答案標記爲正確,請:) – vines 2011-05-26 14:32:06