Boost.Python 中的 bases(基类)功能是 C++ 类型和 Python 类型之间的关键组成部分。这个功能允许您在 Python 类型中公开 C++ 基类的所有方法和属性,使得在 Python 中使用 C++ 类型变得更加方便和灵活。下面我们来看一个简单的 Boost.Python bases 示例程序。
#include <boost/python.hpp>
using namespace boost::python;
class Base {
public:
std::string get_name(){
return "Base";
}
};
class Derived : public Base {
public:
std::string get_name(){
return "Derived";
}
};
BOOST_PYTHON_MODULE(bases_example) {
class_<Base>("Base")
.def("get_name", &Base::get_name)
;
class_<Derived, bases<Base> >("Derived")
.def("get_name", &Derived::get_name)
;
}
上述代码定义了两个 C++ 类型:Base
和 Derived
。Derived
从 Base
继承并覆盖了其中的 get_name
方法。然后我们借助 Boost.Python 模块将这两个类导出到 Python 环境