Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the memory address pointed to by a ctypes pointer

Tags:

python

ctypes

Short version: How can I get the address that a ctypes pointer points to?

Long version: I have registered a python function as a callback with a C library. The C library expects function signature of void (*p_func)(char stat, char * buf, short buf_len) so I register an appropriate python function. When I get into the python function, I want to know the memory address pointed to by buf. How can I do this?

like image 300
Iain Rist Avatar asked Mar 13 '12 15:03

Iain Rist


People also ask

How do you get the address a pointer is pointing to?

You can change the address value stored in a pointer. To retrieve the value pointed to by a pointer, you need to use the indirection operator *, which is known as explicit dereferencing. Reference can be treated as a const pointer. It has to be initialized during declaration, and its content cannot be changed.

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.

How do I find the memory address in Python?

We can get an address using the id() function. id() function gives the address of the particular object.

How do you print the address of a pointer in C++?

How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.


2 Answers

I have fixed this myself by reading the documentation.

I wanted to know the memory location of a block of memory allocated by a library. I had the ctypes pointer that pointed to said block. To get the memory address of the block I used ctypes.addressof(p_block.contents).

The confusion arose around my understanding that p_block.contents != p_block.contents, but then I realised all p_block.contents objects have the same underlying buffer. The address of the underlying buffer is obtained with ctypes.addressof.

like image 84
Iain Rist Avatar answered Oct 14 '22 09:10

Iain Rist


real_adr = cast(anyctypespointer, c_void_p).value

Works for any kind of ctypes pointer - even function pointers etc. which lack .content

like image 5
kxr Avatar answered Oct 14 '22 07:10

kxr