我正在使用Boost Python为C++中的某些类提供python接口(interface)。
我发现这种情况我不确定如何解决:
我有一个具有此成员函数的类:
virtual void visit(const ReportClass r) = 0;
virtual void visit(const unsigned int category) = 0;
virtual void visit(const char* type) = 0;
virtual void visit(const char* name, const unsigned int id, const char &value ) = 0;
virtual void visit(const char* name, const unsigned int id, const unsigned short &value ) = 0;
virtual void visit(const char* name, const unsigned int id, const unsigned int &value ) = 0;
virtual void visit(const char* name, const unsigned int id, const MaskedAddr &value ) = 0;
virtual void visit(const char* name, const unsigned int id, const unsigned long long &value ) = 0;
我对如何实现python-boost部分有点迷茫,我已经看到了如何进行虚函数和重载函数的处理,但是我不知道如何将两者结合起来。
顺便说一句,在示例中,我看到一个返回int的虚函数(例如)应该以这种方式实现:
int f()
{
return this->get_override("f")();
}
就我而言,它们什么也不返回,我想我应该这样实现:
void f()
{
this->get_override("f")();
}
它是否正确?
提前致谢
最佳答案
如果我正确理解了您的问题,则希望将纯虚拟(重载)的方法绑定(bind)到Python,以便可以从python重载它们。您拥有already found的教程对此进行了部分解释。在您的特定情况下,C++和Python与重载不能很好地相互作用。虽然C++允许,但Python禁止。在Python中,不能有两个名称为f
的方法。我们将要做的是使python调用 fork ,以便用户可以从Python实现重写。
我将写一个较小的示例,但是您可以从中抽象出来。
让我们从C++管道开始。您的C++绑定(bind)应如下所示:
struct BaseWrap : Base, boost::python::wrapper<Base> {
int f() {
return this->get_override("__f1__")();
}
int f(int i) {
return this->get_override("__f2__")()
}
int f(const char* s) {
return this->get_override("__f3__")()
}
int f(const char* s, double d) {
return this->get_override("__f4__")()
}
};
//your module code will look like this
BOOST_PYTHON_MODULE(example) {
using namespace boost::python;
class_<BaseWrap, boost::noncopyable>("Base")
.def("f", pure_virtual(((int)(Base::*)())&Base::f))
.def("f", pure_virtual(((int)(Base::*)(int))&Base::f))
.def("f", pure_virtual(((int)(Base::*)(const char*))&Base::f))
.def("f", pure_virtual(((int)(Base::*)(const char*, double))&Base::f))
;
}
我们做了什么?当代码的Python端调用
f(<parameters>)
时,我们将解析为正确的重载方法。然后,此方法将从Python调用Python的__f1__
,__f2__
等,其中方法的内容已被实际编码。要完成绑定(bind),在Python中,您必须继承自
example.Base
并实现__f1__
,__f2__
,__f3__
和__f4__
:class Base(example.Base):
"""Throw here the documentation of Base - don't bother about the C++ stuff"""
def __init__(self,...):
pass
def __f1__(self):
"""Implementation of Base::f()"""
pass
def __f2__(self):
"""Implementation of Base::f(int)"""
pass
def __f3__(self):
"""Implementation of Base::f(const char*)"""
pass
def __f4__(self):
"""Implementation of Base::f(const char*, double)"""
pass
关于c++ - 几个具有不同签名的虚拟成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14624714/