简体   繁体   English

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

[英]How to expose raw byte buffers with Boost::Python?

I've got third party C++ library in which some class methods use raw byte buffers. 我有第三方C ++库,其中一些类方法使用原始字节缓冲区。 I'm not quite sure how to deal in Boost::Python with it. 我不太确定如何处理Boost :: Python。

C++ library header is something like: C ++库头类似于:

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

In stuck with the Boost::Python code... 坚持使用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??? */)))

How do I wrap these raw buffers to expose them as raw strings in Python? 如何将这些原始缓冲区包装在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. 你必须自己编写绑定上的函数,这些函数将从该数据返回一个Py_buffer对象,允许你以只读(使用PyBuffer_FromMemory )或读写(使用PyBuffer_FromReadWriteMemory )从Python预先分配的C / C ++内存。

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);
}

Later on, when you bind CSomeClass , use the static functions above instead of the methods load and save : 稍后,当您绑定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")
    ;

This would look pythonic enough to me. 这对我来说看起来像pythonic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM