我试图将我的C++类暴露给PythonBoost.Python. 下面是我要做的事情的简化版本:
struct Base {
virtual ~Base() {};
virtual char const *Hello() {
printf("Base.Hello\n");
return "Hello. I'm Base.";
};
};
struct Derived : Base {
char const *Hello() {
printf("Derived.Hello\n");
return "Hello. I'm Derived.";
};
Base &test() {
printf("Derived.test\n");
// ...
// After some calculation, we get result reference `instance'
// `instance' can be an instance of Base or Derived.
// ...
return instance;
}
};
我想在python中使用上面的类:
^{pr2}$我不知道解决这个问题的好办法。我刚试过这个:
struct BaseWrapper : Base, wrapper<Base> {
char const *Hello() {
printf("BaseWrapper.Hello\n");
if (override Hello = this->get_override("Hello")) {
return Hello();
}
return Base::Hello();
}
char const *default_Hello() {
printf("BaseWrapper.default_Hello\n");
return this->Base::Hello();
}
};
struct DerivedWrapper : Derived, wrapper<Derived> {
char const *Hello() {
printf("DerivedWrapper.Hello\n");
if (override Hello = this->get_override("Hello")) {
return Hello();
}
return Derived::Hello();
}
char const *default_Hello() {
printf("DerivedWrapper.default_Hello\n");
return this->Derived::Hello();
}
Base &test() {
printf("DerivedWrapper.test\n");
if (override Hello = this->get_override("test")) {
return Hello();
}
return Derived::test();
}
Base &default_test() {
printf("DerivedWrapper.default_test\n");
return this->Derived::test();
}
};
我使用以下代码:
BOOST_PYTHON_MODULE(Wrapper) {
class_<BaseWrapper, boost::noncopyable>("Base")
.def("Hello", &Base::Hello, &BaseWrapper::default_Hello);
class_<DerivedWrapper, boost::noncopyable, bases<Base> >("Derived")
.def("Hello", &Derived::Hello, &DerivedWrapper::default_Hello)
.def("test", &Derived::test, return_value_policy<copy_non_const_reference>());
}
但当我把上面的代码编译成一个.so文件,并在python中使用时
derived = Wrapper.Derived()
derived.test()
它抛出了一个例外:
TypeError: No to_python (by-value) converter found for C++ type: Base
这篇文章和我的错误是一样的,但不同的是,它对我帮助不大。 Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:
这篇文章解决了一个类似的问题,但也没有帮助我。 https://github.com/BVLC/caffe/issues/3494
我有两个问题:
这个代码适用于我:
测试模块:
^{pr2}$相关问题 更多 >
编程相关推荐