[英]How can I upcast a Python derived class to it's c++ base with Boost Python?
I have a c++ class with a pure virtual function which I wrap in the following way using Boost Python: 我有一个带有纯虚函数的c ++类,可以使用Boost Python通过以下方式包装它:
class Model {
virtual double Test() = 0;
};
class ModelWrapper : public Model, public boost::python::wrapper<Model> {
double Test() {
return this->get_override("Test")();
}
};
BOOST_PYTHON_MODULE(mymodule)
{
class_<ModelWrapper, boost::noncopyable>("Model")
.def("Test, pure_virtual(&Model::Test))
;
}
I also have a c++ function that's expecting a Model object as an argument: 我还有一个c ++函数,希望将Model对象作为参数:
double MyFunction(Model& m) {
return m.Test()
}
Now what I would like to do is to make a derived class in Python that overrides the Model::Test function but can still be passed to MyFunction. 现在我想做的是在Python中创建一个派生类,该派生类重写Model :: Test函数,但仍可以传递给MyFunction。 Something like this:
像这样:
from mymodule import *
class NewModel(Model):
def Test(self):
return 0.5
m = NewModel()
print(MyFunction(m))
which I would want to print out 0.5 in this case. 我想在这种情况下打印出0.5。 Instead I get this error:
相反,我得到这个错误:
> ArgumentError: Python argument types in
> mymodule.MyFunction(NewModel) did not match C++ signature:
> MyFunction(Model {lvalue})
I'm not sure what step I'm missing in order for NewModel to be usable where Model is expected. 我不确定要使NewModel在需要Model的地方可用,我缺少什么步骤。 Any insight would be greatly appreciated.
任何见识将不胜感激。
I needed to add 'Model.__init__(self)' to the NewModel __init__ function explicitly. 我需要将'Model .__ init __(self)'添加到NewModel __init__函数中。 After that it worked fine.
之后,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.