7

Using Boost::Python, is there a way to make a raw C++ buffer accessible to Python 3.2 as a bytes object?

There is a Python 2 answer to a very similar question, but the PyBuffer_FromReadWriteMemory function described there no longer exist in Python 3.

Edit: thanks to user2167433's answer, what I actually want is a read only memoryview object, not a bytes object (using a memoryview avoids copying the buffer I believe).

2
  • Why a bytes object? Is the buffer immutable? Commented Apr 14, 2014 at 15:46
  • @delnan Yes the buffer is immutable. Commented Apr 14, 2014 at 15:59

1 Answer 1

15

Python > 3 and Python <= 3.2:

Py_buffer buffer;
int res = PyBuffer_FillInfo(&buffer, 0, data, dataSize, true, PyBUF_CONTIG_RO);
if (res == -1) {
    PyErr_Print();
    exit(EXIT_FAILURE);
}
boost::python::object memoryView(boost::python::handle<>(PyMemoryView_FromBuffer(&buffer)))

Python >= 3.3:

The best way I know how is to use PyMemoryView_FromMemory:

boost::python::object memoryView(boost::python::handle<>(PyMemoryView_FromMemory(data, dataSize, PyBUF_READ)));

memoryview is the Python way to access objects that support the buffer interface.

C API memoryview memoryview class

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.