[英]override a C++ virtual function within Python with Boost.python?
I have a C++ class with a virtual method:我有一个带有虚方法的 C++ 类:
//C++ class A { //C++类A{
public:
A() {};
virtual int override_me(int a) {return 2*a;};
int calculate(int a) { return this->override_me(a) ;}
}; };
What I would like to do is to expose this class to Python with Boost.python, inherit from this class in Python and have the correct overridden called:我想要做的是使用 Boost.python 将这个类公开给 Python,在 Python 中从这个类继承并具有正确的覆盖调用:
#python:
class B(A):
def override_me(self, a):
return 5*a
b = B()
b.calculate(1) # should return 5 instead of 2
I'd like to do the same for pure virtual functions.我想对纯虚函数做同样的事情。 I'm looking for a way to not create any wrapper class in C++ over the class A. Would that be possible ?我正在寻找一种不通过 A 类在 C++ 中创建任何包装类的方法。这可能吗? If yes/ if no, how can I do it ?如果是/如果不是,我该怎么做?
You can provide a thin wrapper around your class that delegates the override_me
method calls to boost::python
-specific override function.您可以在您的类周围提供一个瘦包装器,将override_me
方法调用委托给boost::python
特定的覆盖函数。
Derived class calculate
calls simply call the parent class calculate
method, so when they are called from Python, they call the C++ defined calculate
method, but still allow override_me
method to be overridden from Python:派生类calculate
调用简单地调用父类calculate
方法,所以当从Python调用它们时,它们调用C++定义的calculate
方法,但仍然允许从Python override_me
方法:
#include <boost/python.hpp>
using namespace boost;
using namespace boost::python;
class A {
public:
A() {};
virtual int override_me(int a) {
return 2*a;
};
virtual int calculate(int a) {
return this->override_me(a);
}
};
struct AWrap: A, public boost::python::wrapper<A> {
AWrap() : A() {};
int override_me(int a) override {
if (override f = this->get_override("override_me")) {
return this->get_override("override_me")(a);
} else {
return A::override_me(a);
}
};
int calculate(int a) override {
return A::calculate(a);
}
};
BOOST_PYTHON_MODULE(my_lib)
{
python::class_<AWrap, boost::noncopyable>("A", python::init<>())
.def("override_me", &AWrap::override_me)
.def("calculate", &AWrap::calculate);
}
int main() {}
g++ virtual_override.cpp -fPIC -shared -I/path/to/include/python3 -L/path/to/libpython3 -o my_lib.so -lpython3 -lboost_python3 g++ virtual_override.cpp -fPIC -shared -I/path/to/include/python3 -L/path/to/libpython3 -o my_lib.so -lpython3 -lboost_python3
Example:例子:
This allows for non-pure cases, for example, when override_me isn't overridden, the default function is called:这允许非纯情况,例如,当 override_me 未被覆盖时,将调用默认函数:
import my_lib
class B(my_lib.A):
pass
b = B()
print (b.calculate(1))
2 2
But virtual overrides are possible from Python:但是可以从 Python 进行虚拟覆盖:
import my_lib
class B(my_lib.A):
def override_me(self, a):
return 5*a
b = B()
print (b.calculate(1))
5 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.