Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes: construct pointer from arbitrary integer

Tags:

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

like image 351
sebulba Avatar asked Apr 25 '11 22:04

sebulba


People also ask

What is Ctypes pointer?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

What is CDLL in Python?

It is a big C++ codebase with a (very) thin python wrapper which uses CDLL to load the C++ and call some C functions that are available to allow primitive python scripting of the code.

What is C_char_p?

c_char_p is a subclass of _SimpleCData , with _type_ == 'z' . The __init__ method calls the type's setfunc , which for simple type 'z' is z_set . In Python 2, the z_set function (2.7.


1 Answers

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 
like image 161
samplebias Avatar answered Nov 14 '22 02:11

samplebias