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