Expose C++ buffer as Python 3 bytes
-
26-12-2019 - |
문제
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).
해결책
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.
제휴하지 않습니다 StackOverflow