[英]Boost.Python and C++ std::vector of pointers
I'm using Boost.Python to create a wrapper for my C++ library, and I'm having some troubles, googling all the day did not produc any results. 我正在使用Boost.Python为我的C ++库创建一个包装器,我遇到了一些麻烦,谷歌搜索一整天都没有产生任何结果。 For example, I have the following code: 例如,我有以下代码:
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>());
}
So, I compile it, import in python and try this: 所以,我编译它,在python中导入并试试这个:
b = mylib.Base() b.func() b = mylib.Base()b.func()
d = mylib.makeDerived() d.func() d = mylib.makeDerived()d.func()
The first line, as expected, throws an exception saying that b.func() is pure virtual, and the second line prints out 正如预期的那样,第一行抛出一个异常,说b.func()是纯虚拟的,第二行打印出来
Derived::func() 派生:: FUNC()
And that's ok. 那没关系。
But the code 但是代码
dlist = mylib.makeDerivedVec()
for d in dlist:
d.func()
does not work, and Python throws an exception: 不起作用,Python引发异常:
TypeError: No to_python (by-value) converter found for C++ type: Base*
Why it handled correctly the Base* returned by makeDerived() and refuses to work with Base* contained in std::vector? 为什么它正确处理了makeDerived()返回的Base *并且拒绝使用std :: vector中包含的Base *? How can I make it work? 我怎样才能使它工作?
You can fix this by registering Base*
as a type that can be used to point to a BaseWrapper*
: 您可以通过将Base*
注册为可用于指向BaseWrapper*
的类型来解决此问题:
class_<BaseWrapper, noncopyable, Base*>("Base")
.def("func", pure_virtual(&Base::func));
But it seems that this means that Base
can't have a pure virtual function... 但似乎这意味着Base
无法拥有纯粹的虚拟功能......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.