且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Boost python包装C ++模板类

更新时间:2021-12-18 21:33:02

最简单的方法是从STL向量接口继承并使用Boost Python vector_indexing_suite ,否则,您必须手动实现切片对于Python界面的操作不是那么快速而琐碎.

The easiest way for your task is to inherit from STL vector interface and use Boost Python vector_indexing_suite, otherwise you had to manually implement slice operations for Python interface that is not so fast and trivial.

但是对于最初的问题包装C ++模板类,然后在包装模板时我遇到了下一个问题:

But as for the original question Wrap C++ template class then I faced with the next problem when wrapped templates:

template<typename LinksT>
class Base {
public:
  virtual ~Base()  {}
  virtual Base* x() = 0;
};

template<typename LinksT>
class BaseWrap : public Base<LinksT>, public wrapper<Base<LinksT>> {
public:
  virtual Base<LinksT>* x() { return this->get_override("x")(); }
};

BOOST_PYTHON_MODULE(xxx)
{
    class_<BaseWrap<LinksT>, noncopyable>("Base", no_init)
      .def("x", pure_virtual(&Base<LinksT>::x), return_internal_reference<>())
      ;
}

无法在Linux下的GCC 4.8上编译,认为对于直接类来说,它可以正常工作:

fails to compile on GCC 4.8 under Linux, thought for direct classes it works fine:

class Base {
public:
  virtual ~Base()  {}
  virtual Base* x() = 0;
};

class BaseWrap : public Base, public wrapper<Base> {
public:
  virtual Base* x() { return this->get_override("x")(); }
};

BOOST_PYTHON_MODULE(xxx)
{
    class_<BaseWrap, noncopyable>("Base", no_init)
      .def("x", pure_virtual(&Base::x), return_internal_reference<>())
      ;
}

有2个问题:

  1. 我必须指定 -ftemplate-backtrace-limit = 64(默认值为10)编译器标志,才能实例化更多内部模板
  2. BOOST_PYTHON_MODULE(xxx) 声明之前,我必须实例化模板:
  1. I had to specify -ftemplate-backtrace-limit=64 (default it's 10) compiler flag to allow instantiate more inner templates
  2. I had to instantiate template before the BOOST_PYTHON_MODULE(xxx) declaration:

template class BaseWrap<SimpleLinks>;
BOOST_PYTHON_MODULE(xxx)
{ ...

然后正常工作.