Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose C++ buffer as Python 3 bytes

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).

like image 210
Rob Agar Avatar asked Apr 14 '14 15:04

Rob Agar


1 Answers

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

like image 158
brookskd Avatar answered Sep 21 '22 11:09

brookskd