将C++缓冲区公开为Python 3字节

Rob*_*gar 5 c++ boost-python python-3.x python-3.2

使用Boost :: Python,有没有办法让Python 3.2作为bytes对象可以访问原始C++缓冲区?

对于一个非常相似的问题,有一个Python 2答案,但PyBuffer_FromReadWriteMemoryPython 3中描述的函数不再存在.

编辑:感谢user2167433的回答,我真正想要的是一个只读的memoryview对象,而不是一个bytes对象(使用memoryview避免复制我相信的缓冲区).

bro*_*skd 12

Python> 3和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)))
Run Code Online (Sandbox Code Playgroud)

Python> = 3.3:

我知道如何使用PyMemoryView_FromMemory的最好方法:

boost::python::object memoryView(boost::python::handle<>(PyMemoryView_FromMemory(data, dataSize, PyBUF_READ)));
Run Code Online (Sandbox Code Playgroud)

memoryview是访问支持缓冲区接口的对象的Python方法.

C API memoryview memoryview类