【问题标题】:Boost.Python: expose class member which is a pointerBoost.Python:公开作为指针的类成员
【发布时间】:2016-04-12 00:26:35
【问题描述】:

我有一个想要暴露给 python 的 C++ 类。 (假设这个类已经被编写并且不能轻易修改)。在这个类中,有一个成员是一个指针,我也想公开那个成员。这是代码的最小版本。

struct C {
  C(const char* _a) { a = new std::string(_a); }
  ~C() { delete a; }
  std::string *a;
};


BOOST_PYTHON_MODULE(text_detection)
{
  class_<C>("C", init<const char*>())
      .def_readonly("a", &C::a);
}

它编译正常,除了当我尝试访问该字段时出现 python 运行时错误:

>>> c = C("hello")
>>> c.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No to_python (by-value) converter found for C++ type: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >*

这是可以理解的。但问题是,是否有可能通过 boost python 暴露成员指针a?怎么做?

提前非常感谢!

【问题讨论】:

    标签: c++ boost boost-python


    【解决方案1】:

    不要使用def_readonly,而是使用带有自定义getter 的add_property。您需要将 getter 包装在 make_function 中,并且由于 getter 返回 const&amp;,您还必须指定 return_value_policy

    std::string const& get_a(C const& c)
    {
      return *(c.a);
    }
    
    BOOST_PYTHON_MODULE(text_detection)
    {
      using namespace boost::python;
      class_<C>("C", init<const char*>())
        .add_property("a", make_function(get_a, return_value_policy<copy_const_reference>()))
        ;
    }
    

    Live demo

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 2014-08-25
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多