I want to extract the integer address that a ctypes.c_char_p
instance points to.
For example, in
>>> import ctypes
>>> s = ctypes.c_char_p("hello")
>>> s
c_char_p(4333430692)
the value I'd like to fetch is 4333430692 — the address of the string hello\0
in memory:
(lldb) x 4333430692
0x1024ae7a4: 68 65 6c 6c 6f 00 5f 70 00 00 00 00 05 00 00 00 hello._p........
I've read the ctypes docs, but there doesn't seem to be any way of doing that. The closest is ctypes.addressof
, but that only gives me the location of the pointer, of course.
The reason why I want this is because I'm calling some C functions that actually expects raw addresses encoded as integers (whose size equals the native pointer width).
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.
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.
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.
You could just cast it to c_void_p
and get the value:
>>> ctypes.cast(s, ctypes.c_void_p).value
4333430692
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With