10
votes

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?

2
It would help if you posted some source code using the {} tags. Thanks. - octopusgrabbus
I think you are looking for the "id" of the function docs.python.org/library/functions.html#id In [1]: a = 4 In [2]: id(a) Out[2]: 10019764 - Garrett Berg
I am after the address of a bit of memory pointed to by a ctypes.POINTER object that has been passed to me by a c library, not the id of a purely python object. - Iain Rist
I have fixed this myself with ctypes.addressof(buf.contents) but I can't answer my own question yet. - Iain Rist
Gotcha! Matsalams! - eigenfield

2 Answers

14
votes

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.

4
votes
real_adr = cast(anyctypespointer, c_void_p).value

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