[英]Boost.Python: expose class member which is a pointer
I have a C++ class that would like to expose to python. 我有一个想要暴露给python的C ++类。 (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: 编译好了,除了我尝试访问该字段时出现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> >*
which is understandable. 这是可以理解的。 But the question is that is it possible to expose member pointer
a
through boost python at all? 但问题是,是否有可能暴露成员指针
a
通过提升蟒蛇呢? And how? 如何?
Thanks a lot in advance! 非常感谢提前!
Instead of using def_readonly
, use add_property
with a custom getter. 而不是使用
def_readonly
,将add_property
与自定义getter一起使用。 You'll need to wrap the getter in make_function
, and since the getter is returning a const&
you must also specify a return_value_policy
. 你需要将getter包装在
make_function
,因为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>()))
;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.