gpt4 book ai didi

python - 如何使用 Boost::Python 公开原始字节缓冲区?

转载 作者:太空狗 更新时间:2023-10-29 18:06:08 26 4
gpt4 key购买 nike

我有第三方 C++ 库,其中一些类方法使用原始字节缓冲区。我不太确定如何在 Boost::Python 中处理它。

C++ 库头类似于:

class CSomeClass
{
public:
int load( unsigned char *& pInBufferData, int & iInBufferSize );
int save( unsigned char *& pOutBufferData, int & iOutBufferSize );
}

坚持使用 Boost::Python 代码...

class_<CSomeClass>("CSomeClass", init<>())
.def("load", &CSomeClass::load, (args(/* what do I put here??? */)))
.def("save", &CSomeClass::save, (args(/* what do I put here??? */)))

如何包装这些原始缓冲区以在 Python 中将它们公开为原始字符串?

最佳答案

您必须自己编写绑定(bind)函数,返回 Py_buffer来自该数据的对象,允许您以只读方式(使用 PyBuffer_FromMemory)或读写(使用 PyBuffer_FromReadWriteMemory)您从 Python 预分配的 C/C++ 内存。

这就是它的样子(欢迎反馈):

#include <boost/python.hpp>

using namespace boost::python;

//I'm assuming your buffer data is allocated from CSomeClass::load()
//it should return the allocated size in the second argument
static object csomeclass_load(CSomeClass& self) {
unsigned char* buffer;
int size;
self.load(buffer, size);

//now you wrap that as buffer
PyObject* py_buf = PyBuffer_FromReadWriteMemory(buffer, size);
object retval = object(handle<>(py_buf));
return retval;
}

static int csomeclass_save(CSomeClass& self, object buffer) {
PyObject* py_buffer = buffer.ptr();
if (!PyBuffer_Check(py_buffer)) {
//raise TypeError using standard boost::python mechanisms
}

//you can also write checks here for length, verify the
//buffer is memory-contiguous, etc.
unsigned char* cxx_buf = (unsigned char*)py_buffer.buf;
int size = (int)py_buffer.len;
return self.save(cxx_buf, size);
}

稍后,当您绑定(bind) CSomeClass 时,使用上面的静态函数代替方法 loadsave:

//I think that you should use boost::python::arg instead of boost::python::args
// -- it gives you better control on the documentation
class_<CSomeClass>("CSomeClass", init<>())
.def("load", &csomeclass_load, (arg("self")), "doc for load - returns a buffer")
.def("save", &csomeclass_save, (arg("self"), arg("buffer")), "doc for save - requires a buffer")
;

这对我来说看起来足够 pythonic。

关于python - 如何使用 Boost::Python 公开原始字节缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com