Boost.Python:公开作为指针的类成员

Yin*_*ong 3 c++ boost boost-python

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

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);
}
Run Code Online (Sandbox Code Playgroud)

它编译正常,只是当我尝试访问该字段时出现 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> >*
Run Code Online (Sandbox Code Playgroud)

这是可以理解的。但问题是,是否有可能a通过 Boost Python 公开成员指针?如何?

Pra*_*ian 5

不要使用,而是与自定义 getter 一起def_readonly使用。add_property您需要将 getter 包装在 中make_function,并且由于 getter 返回 aconst&您还必须指定 a 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>()))
    ;
}
Run Code Online (Sandbox Code Playgroud)

现场演示