这里主要使用到了类的继承封装
boost::python::class_<T,boost::python:bases<Base>>("inheritance_class_name")
#include <iostream>
#include <string>
class Base //基类
{
public:
virtual std::string name() const { return "Base"; }
virtual ~Base() {}
};
class Derived : public Base //继承类,公有继承
{
public:
virtual std::string name() const { return "Derived"; }
};
void fb(Base *b) //多态的调用,父指针调用子类
{
std::cout << b->name() << " called." << std::endl;
}
void fd(Derived *d)
{
std::cout << "Derived " << d->name() << " called." << std::endl;
}
Base* factory()
{
return new Derived;
}
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(boost_eg)
{
class_<Base, boost::noncopyable>("Base") //父类的导入
.def("name", &Base::name)
;
class_<Derived, bases<Base> >("Derived") //子类的导入,父类虚函数导入了,子类就不需要导入
;
def("fb", fb);
def("fd", fd);
def("factory", factory, return_value_policy<manage_new_object>());
}
python代码
#!/usr/bin/env python
import boost_eg
b = boost_eg.Base() #创建父类对象
d = boost_eg.Derived() #创建子类对象
boost_eg.fb(b) #传入父类对象,调用父类的name函数
boost_eg.fb(d) #传入子类对象,调用子类的name函数(多态)
# not possible, fd is only for Derived objects
# boost_eg.fd(b)
boost_eg.fd(d) #
x = boost_eg.factory() #返回子类对象
boost_eg.fb(x) #使用子类对象,多态
运行结果
Base called.
Derived called.
Derived Derived called.
Derived called.