Boost.Python: 公开 class 成员,它是一个指针
Boost.Python: expose class member which is a pointer
我有一个 C++ class 想要暴露给 python。 (假设这个 class 已经写好了,不能轻易修改)。在这个class中,有一个成员是指针,我也想公开那个成员。这是代码的最小版本。
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> >*
这是可以理解的。但问题是,到底有没有可能通过boostpython暴露成员指针a
呢?以及如何?
非常感谢!
不使用 def_readonly
,而是使用带有自定义 getter 的 add_property
。您需要将 getter 包裹在 make_function
, and since the getter is returning a const&
you must also specify 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>()))
;
}
我有一个 C++ class 想要暴露给 python。 (假设这个 class 已经写好了,不能轻易修改)。在这个class中,有一个成员是指针,我也想公开那个成员。这是代码的最小版本。
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> >*
这是可以理解的。但问题是,到底有没有可能通过boostpython暴露成员指针a
呢?以及如何?
非常感谢!
不使用 def_readonly
,而是使用带有自定义 getter 的 add_property
。您需要将 getter 包裹在 make_function
, and since the getter is returning a const&
you must also specify 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>()))
;
}