8

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.

Kos
  • 70,399
  • 25
  • 169
  • 233
  • Can you give some example code? – ebarr Dec 13 '12 at 13:18
  • 1
    There we go, I hope it's clear now – Kos Dec 13 '12 at 14:06
  • So this may be useful http://stackoverflow.com/questions/121396/accessing-object-memory-address . I have tried playing around with the suggestions therein, but with limited success. The trick is most likely to write a PythonC_API function to take the buffer and return its address. That should be relatively easy to do. – ebarr Dec 13 '12 at 22:49
  • In the case of a `void*`, a `str`/`unicode` (Python 2.x) or `bytes`/`str` (Python 3.x) can just be passed directly to the function. – Mark Tolonen Mar 16 '23 at 00:15

1 Answers1

0

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.

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120