1

I'd like to get a pointer to raw binary data of bytes, bytearray, or memoryview instance via ctypes and Python API.

For reading, (c_char * len(b)).from_buffer(b) works in Python 3. For writing, I used the following:

buffer = c_void_p()
length = c_ssize_t()
pythonapi.PyObject_AsReadBuffer(py_object(b), byref(buffer), byref(length))

However I found out that the code doesn't work in Python 2.7 with memoryview.

2
  • How about ctypes.string_at() ? Commented Aug 2, 2014 at 18:32
  • @mdurant That does the opposite. Commented Aug 4, 2014 at 6:56

1 Answer 1

3

Currently, I use a Python buffer structure defined via ctypes and a Python API function PyObject_GetBuffer to get the buffer from arbitrary compatible object. My Python buffer structure object is then transformed to c_char array and created buffer object is relased using PyBuffer_Release. See https://github.com/Drekin/win-unicode-console/blob/master/win_unicode_console/buffer.py.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.