Boost_Python Notes
文章目录
Classes
Constructor 构造函数
多个构造函数
使用def 添加第二个及以后的Constructor
| |
禁用构造函数
使用no_init
| |
数据成员
普通类型
- def_readwrite
1 2 3int a; // public def_readwrite("a", &World::a);const 类型
def_readonly
1 2 3const int a; // public def_readonly("a", &World::a);
属性函数(getter, setter)
直接指定getter, setter即可
使用add_property
1 2 3 4 5 6 7 8 9 10 11 12struct Num { Num(); float get() const; void set(float value); }; class_<Num>("Num") .add_property("rovalue", &Num::get) .add_property("value", &Num::get, &Num::set);- 注意
- 要么只有getter
- 要么getter, setter都有
继承问题
普通继承
直接声明继承关系即可
- class_<Derived, bases<Base>>(…)
| |
多态与虚函数
非纯虚函数(有定义default implementations)
在纯虚函数的基础上在加一些修饰
- override f = this->get_override("f") 判断是否是子类调用重载函 数
| |
- 同时保留原来的版本default_f
Boost.Python 添加 非纯虚函数的特殊格式
1 2 3class_<BaseWrap, boost::noncopyable>("Base") .def("f", &Base::f, &BaseWrap::default_f) ;完全实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41// * 抽象类 struct Base { virtual ~Base() {} // 纯虚函数 virtual int f() { return 0; }; }; // * 包装方法 struct BaseWrap : Base, wrapper<Base> { int f() { // 1) 获取重载的情况,即子类的调用情况 if (override f = this->get_override("f")) // for unix like return f(); // for windows return call<char const*>(f.ptr()); // 2) 非重载的情况,即当前基类Base 的默认定义f return this->f(); } // 存储默认定义 int default_f() { return this->Base::f(); } }; // * Boost.Python 声明抽象类的方法 // 同时暴露(exposing) Base::f 和 &BaseWrap::default_f, 这是Boost.Python 的一种特例 class_<BaseWrap, boost::noncopyable>("Base") .def("f", &Base::f, &BaseWrap::default_f) ;
运算符重载
| |
Python 的特殊函数
str, abs, pow, float
- 这些特殊函数,Boost.Python 有规定的形式,因此要按照标准方式来声明
注意
- 使用输出流运算符 << 实现python str 函数功能
| |
文章作者
上次更新 2021-07-23 (01539ff)