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).
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)))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With