Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the address of a ctypes object

Tags:

python

ctypes

I have a buffer like:

bufstr = ctypes.create_string_buffer("Test", 32)

How I obtain the address of that buffer? i.e. the one displayed if I do:

print bufstr

like:

<ctypes.c_char_Array_32 object at 0x042ACAD0>

I know I can pass it with byref(), for example; but what if I just want to get that address (aside from slicing that string!)?

Thanks!

like image 532
Anonymous Coward Avatar asked Mar 07 '11 03:03

Anonymous Coward


People also ask

What is ctypes CDLL?

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.

Does ctypes work with C++?

ctypes is the de facto standard library for interfacing with C/C++ from CPython, and it provides not only full access to the native C interface of most major operating systems (e.g., kernel32 on Windows, or libc on *nix), but also provides support for loading and interfacing with dynamic libraries, such as DLLs or ...

What is C_ubyte?

A cubit is an ancient unit based on the forearm length from the middle fingertip to the elbow bottom. Cubits of various lengths were employed in many parts of the world in antiquity, during the Middle Ages and as recently as Early Modern Times.


2 Answers

Use ctypes.addressof.

ctypes.addressof(bufstr)
like image 137
John Flatness Avatar answered Nov 14 '22 23:11

John Flatness


I believe:

ctypes.addressof(bufstr)

should do it. Note that the address mentioned in toString is for the Python object, not the C memory.

like image 45
Edward Z. Yang Avatar answered Nov 14 '22 23:11

Edward Z. Yang