Domanda

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

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top