先前翻译过一篇boost.python 继承方面的官方教程,现在自己研究了下,发现了一些问题。
首先我的boost直接使用官方给的安装工具,在线下载了所需的二进制dll,直接使用的,出现了一些问题,比如c++中使用printf和cout输出的内容全不可见,然后我想了个折衷的办法,将输出的内容写文件,反正编译的时候没少生成很多小的碎文件,也不在乎多这一个。
就举其中例子吧:
void write2Log( char * str ) { FILE * output = fopen( "log.txt" , "ab"); fprintf( output , str ); fclose( output); } struct Base { virtual ~Base() {} virtual int f() { write2Log("====4====\n"); return 0; } }; struct BaseWrap : Base, wrapper<Base> { int f() { write2Log("====1====\n"); if (override f = this->get_override("f")) return f(); // *note* write2Log("====2====\n"); return Base::f(); } int default_f() { write2Log("====3====\n"); return this->Base::f(); } }; class_<BaseWrap, boost::noncopyable>("Base") .def("f", &Base::f, &BaseWrap::default_f);
调用 时使用的Python脚本:
a = hello.Base() a.f() class Derived( hello.Base): def f(self): print 'hello world' b = Derived() b.f() super( Derived , b ).f()
0 hello world 0
记录信息:
**************new test**************** ====4==== ====4====
1.python中父子函数重名,子类函数一定会覆盖父类函数,同名函数只能存在一个。子类直接覆盖就好了,使用super函数直接可以调用父类函数,这样大费周张写boost.python有什么作用?
2.看暴露函数的部分,
class_<BaseWrap, boost::noncopyable>("Base") .def("f", &Base::f, &BaseWrap::default_f);使用python调用时,给出两个可选项,&Base::f和 &BaseWrap::default_f , 唯独没有&BaseWrap::f , 而这个函数正是我们费半天劲写的,却没有提供给python调用,这是为什么?
3.接下来是最精髓的了,我把暴露的函数变了变
class_<BaseWrap, boost::noncopyable>("Base") .def("f", &BaseWrap::default_f, &BaseWrap::f);默认先调用后面的然后调用
super( Derived , b ).f()python给我回答:
记录信息:
====1==== ====1==== ====1==== ====1==== ...
4.直接
class_<Base, boost::noncopyable>("oldBase") .def("f", &Base::f);调用的结果,和写那一堆效果一样。
彻底无语了,作者这样设计,一定有它的作用,可我还是暂时无法理解。
没办法,尽量把c++的代码当模块调用,不要打算继承了。