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?
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.
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.
We can get an address using the id() function. id() function gives the address of the particular object.
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.
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
.
real_adr = cast(anyctypespointer, c_void_p).value
Works for any kind of ctypes pointer - even function pointers etc. which lack .content
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