简体   繁体   中英

const void* pointer in ctypes

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

How to deal with non-writable buffers, however? How to form a const pointer that I can pass to C code that expects a const void* without resorting to making a writable copy of the non-writable buffer?

I considered c_void_p.from_address but buffers (and memoryviews) don't seem to expose their address.


Some clarification:

>>> 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?

That would work with void some_api(const void* read_only_data) like:

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

The method with from_buffer_copy works, but needs to copy the buffer first. I'm looking to way to work around the requirement of the buffer being writable, because nobody is going to write there and I want to avoid redundant copying of data.

You can cast a Python string to char* with ctypes, and that points to actual memory there Python string data is stored.

Feel free to double-cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM