前言
學習中如果碰到問題,參考官網例子:
D:/boost_1_61_0/libs/python/test
參考:Boost.Python 中英文文檔。
利用Boost.Python實現Python C/C++混合編程
關于python與C++混合編程,事實上有兩個部分
extending 所謂python 程序中調用c/c++代碼, 其實是先處理c++代碼, 預先生成的動態鏈接庫, 如example.so, 而在python代碼中import example;即可使用c/c++的函數 . embedding c++代碼中調用 python 代碼.兩者都可以用 python c 轉換api,解決,具體可以去python官方文檔查閱,但是都比較繁瑣.
對于1,extending,常用的方案是boost.python以及swig.
swig是一種膠水語言,粘合C++,PYTHON,我前面的圖形顯示二叉樹的文章中提到的就是利用pyqt作界面,調用c++代碼使用swig生成的.so動態庫.
而boost.python則直接轉換,可以利用py++自動生成需要的wrapper.關于這方面的內容的入門除了boost.python官網,中文的入門資料推薦
下面話不多說了,來一起看看詳細的介紹吧
導出函數
#include<string>#include<boost/python.hpp>using namespace std;using namespace boost::python;char const * greet(){ return "hello,world";}BOOST_PYTHON_MODULE(hello_ext){ def("greet", greet);}
python:
import hello_extprint hello_ext.greet()
導出類:
導出默認構造的函數的類
c++
#include<string>#include<boost/python.hpp>using namespace std;using namespace boost::python;struct World{ void set(string msg) { this->msg = msg; } string greet() { return msg; } string msg;};BOOST_PYTHON_MODULE(hello) //導出的module 名字{ class_<World>("World") .def("greet", &World::greet) .def("set", &World::set);}
python:
import hello planet = hello.World() # 調用默認構造函數,產生類對象planet.set("howdy") # 調用對象的方法print planet.greet() # 調用對象的方法
構造函數的導出:
#include<string>#include<boost/python.hpp>using namespace std;using namespace boost::python;struct World{ World(string msg):msg(msg){} //增加構造函數 World(double a, double b):a(a),b(b) {} //另外一個構造函數 void set(string msg) { this->msg = msg; } string greet() { return msg; } double sum_s() { return a + b; } string msg; double a; double b;};BOOST_PYTHON_MODULE(hello) //導出的module 名字{ class_<World>("World",init<string>()) .def(init<double,double>()) // expose another construct .def("greet", &World::greet) .def("set", &World::set) .def("sum_s", &World::sum_s);}
python 測試調用:
import helloplanet = hello.World(5,6)planet2 = hello.World("hollo world")print planet.sum_s()print planet2.greet()
新聞熱點
疑難解答