Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the pointer address of a ctypes.c_char_p instance

Tags:

python

ctypes

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).

like image 536
csl Avatar asked Aug 26 '15 19:08

csl


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 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.

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.


1 Answers

You could just cast it to c_void_p and get the value:

>>> ctypes.cast(s, ctypes.c_void_p).value
4333430692
like image 100
tynn Avatar answered Sep 22 '22 08:09

tynn