Boost.Python: expose class member which is a pointer

时间:2016-04-12 00:26:35

标签: c++ boost boost-python

I have a C++ class that would like to expose to python. (Assuming this class has already been written and couldn't be easily modified). In this class, there is a member which is a pointer, and I would like to expose that member as well. Here is a minimal version of the code.

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

It compiles okay, except that there is a python runtime error when I tried to access that field:

>>> 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> >*

which is understandable. But the question is that is it possible to expose member pointer a through boost python at all? And how?

Thanks a lot in advance!

1 个答案:

答案 0 :(得分:3)

不使用def_readonly,而是将add_property与自定义getter一起使用。您需要在make_function中包含getter,并且由于getter返回const&,您还必须指定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