Const void * pointer in ctypes

If I have a writable buffer , I can use the ctypes.c_void_p.from_buffer function to get a pointer to this buffer.

How to work with unpirable buffers, however? How to generate a const pointer that I can pass to C code that expects const void* without resorting to creating a writable copy of an unwritable buffer?

I counted c_void_p.from_address , but the buffers (and memory) do not display their address.


Some explanations:

 >>> import ctypes >>> b = buffer("some data that supports the buffer interface, like a str") >>> ptr = ctypes.c_void_p.from_buffer(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: buffer is read-only >>> ptr = ctypes.c_void_p.from_buffer_copy(b) # works, but has to copy data >>> ptr = ctypes.CONST(c_void_p).from_buffer(b) # (I'm making this one up) >>> ptr = ctypes.c_void_p.from_address(???) # could work; how to get addr? 

This will work with void some_api(const void* read_only_data) as follows:

 >>> ctypes.cdll.LoadLibrary(some_lib).some_api(ptr) 

The method with from_buffer_copy works, but first you need to copy the buffer. I am looking for a way around the requirement that the buffer be writable, because no one is going to write there, and I want to avoid over-copying the data.

+6
source share
1 answer

You can overlay a Python string with char* using ctypes, and this points to the real memory where the Python string data is stored.

Avoid double casting.

0
source

All Articles