我正在使用Boost.Python为我的C ++库创建一个包装器,我遇到了一些麻烦,谷歌搜索一整天都没有产生任何结果。例如,我有以下代码:
class Base
{
public:
virtual void func() = 0;
};
class Derived : public Base
{
public:
virtual void func()
{
cout << "Derived::func()"<< endl;
}
};
// wrapper for Base
struct BaseWrapper : Base, python::wrapper<Base>
{
virtual void func()
{
this->get_override("func");
}
};
Base* makeDerived()
{
return new Derived;
}
vector<Base*>* makeDerivedVec()
{
vector<Base*> *v = new vector<Base*>;
v->push_back(new Derived);
v->push_back(new Derived);
v->push_back(new Derived);
return v;
}
BOOST_PYTHON_MODULE(mylib)
{
// export Base
class_<BaseWrapper, noncopyable>("Base")
.def("func", pure_virtual(&Base::func));
class_<vector<Base*> >("BasePtrVec")
.def(vector_indexing_suite<vector<Base*> >());
// export Derived
class_<Derived, bases<Base> >("Derived")
.def("func", &Derived::func);
// export makeDerived()
def("makeDerived", &makeDerived, return_value_policy<manage_new_object>());
// export makeDerivedVec()
def("makeDerivedVec", &makeDerivedVec, return_value_policy<manage_new_object>());
}
所以,我编译它,在python中导入并试试这个:
b = mylib.Base()b.func()
d = mylib.makeDerived()d.func()
正如预期的那样,第一行抛出一个异常,说b.func()是纯虚拟的,第二行打印出来
派生:: FUNC()
没关系。
但代码
dlist = mylib.makeDerivedVec()
for d in dlist:
d.func()
不起作用,Python抛出异常:
TypeError: No to_python (by-value) converter found for C++ type: Base*
为什么它正确处理了makeDerived()返回的Base *并且拒绝使用std :: vector中包含的Base *?我怎样才能使它工作?
答案 0 :(得分:3)
您可以通过将Base*
注册为可用于指向BaseWrapper*
的类型来解决此问题:
class_<BaseWrapper, noncopyable, Base*>("Base")
.def("func", pure_virtual(&Base::func));
但似乎这意味着Base
不能拥有纯虚函数......