如何公开原始字节的缓冲区与升压:: Python的? [英] How to expose raw byte buffers with Boost::Python?
问题描述
我有第三方C ++库中,一些类方法使用原始字节的缓冲区。我不太确定如何处理在升压:: Python的吧。
I've got third party C++ library in which some class methods use raw byte buffers. I'm not quite sure how to deal in Boost::Python with it.
C ++库头是一样的东西:
C++ library header is something like:
class CSomeClass
{
public:
int load( unsigned char *& pInBufferData, int & iInBufferSize );
int save( unsigned char *& pOutBufferData, int & iOutBufferSize );
}
在套牢了boost :: Python的code ...
In stuck with the Boost::Python code...
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原始字符串?
How do I wrap these raw buffers to expose them as raw strings in Python?
推荐答案
您已经写了,你自己,你的绑定功能,将返回<一个href=\"http://docs.python.org/2/c-api/buffer.html?highlight=buffer#buffers-and-memoryview-objects\">Py_buffer从数据对象,允许你要么只读(使用 PyBuffer_FromMemory
)或读写(使用 PyBuffer_FromReadWriteMemory
)您的pre-分配的C / C ++内存从Python的。
You have to write, yourself, functions on your bindings that will return a Py_buffer object from that data, allowing your to either read-only (use PyBuffer_FromMemory
) or read-write (use PyBuffer_FromReadWriteMemory
) your pre-allocated C/C++ memory from Python.
这是它是如何将看起来像(反馈最受欢迎):
This is how it is going to look like (feedback most welcome):
#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);
}
后来,当您绑定 CSomeClass
,请使用上面的替代方法负荷
和<$静态功能C $ C>保存:
Later on, when you bind CSomeClass
, use the static functions above instead of the methods load
and save
:
//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")
;
这看起来Python的足够给我。
This would look pythonic enough to me.
这篇关于如何公开原始字节的缓冲区与升压:: Python的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!