av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

Python綁定C++程序具體實(shí)現(xiàn)方法淺談

Python編程語言的應(yīng)用范圍比較廣泛,應(yīng)用方式靈活,可以很方便的幫助開發(fā)人員實(shí)現(xiàn)一些特定的功能需求。比如今天為大家介紹的有關(guān)Python綁定C++程序的相關(guān)操作,大家就可以從中了解到這一語言的應(yīng)用特點(diǎn)。#t#

創(chuàng)新互聯(lián)從2013年創(chuàng)立,先為綏江等服務(wù)建站,綏江等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為綏江企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

很多時候需要給C++程序提供一種使用上的靈活性,腳本語言在這里就變得很重要了。采用Boost.Python為C++程序加一層shell,比較簡單、簡潔,對原有的C++代碼也沒有侵入性。今天試了一下,感覺不錯,可以把它集成在現(xiàn)在正在做的項目中。

為Python綁定C++程序過程基本上如下:

(1)為C++類編寫一個Boost.Python wrapper

(2)編譯成so

(3)可以在python中調(diào)用了

針對David Abrahams的例子,偶的源文件如下:

Python綁定C++程序例1:hello world 函數(shù)

(1)hello.cpp

 
 
 
  1. #include < stdexcept> 
  2. char const* greet(unsigned x)  
  3. {  
  4. static char const* const msgs[] = { "hello", "Boost.Python", "world!" };  
  5. if (x > 2)   
  6. throw std::range_error("greet: index out of range");  
  7. return msgs[x];  

(2)hello_wrap.cpp

 
 
 
  1. #include < boost/python.hpp> 
  2. using namespace boost::python;  
  3. char const* greet(unsigned x);  
  4. BOOST_PYTHON_MODULE(hello)  
  5. {  
  6. def("greet", greet, "return one of 3 parts of a greeting");  

(3)makefile

 
 
 
  1. PYTHON_INCLUDE_FLAGS = \  
  2. -I/usr/include/python2.4  
  3. LIB_FLAGS = \  
  4. -lboost_python  
  5. SOURCE = \  
  6. hello.cpp hello_wrap.cpp  
  7. all:${SOURCE}  
  8. g++ ${PYTHON_INCLUDE_FLAGS} ${SOURCE} ${LIB_FLAGS} -shared -o hello.so  
  9. clean:  
  10. rm -f hello *.o *.out *.so 

(4)hello.py

 
 
 
  1. import hello  
  2. for x in range(3):  
  3. print hello.greet(x) 

Python綁定C++程序例2:hello world類

(1)hello_class.cpp

 
 
 
  1. #include < boost/python.hpp> 
  2. #include < iostream> 
  3. using namespace std;  
  4. using namespace boost::python;  
  5. class World  
  6. {  
  7. public:  
  8. void set(std::string msg) { this->msgmsg = msg; }  
  9. void greet()   
  10. {  
  11. cout < <  this->msg < <  endl;   
  12. }  
  13. string msg;  
  14. };  
  15. BOOST_PYTHON_MODULE(hello)  
  16. {  
  17. class_< World> w("World");  
  18. w.def("greet", &World::greet);  
  19. w.def("set", &World::set);  
  20. }; 

(2)makefile

 
 
 
  1. PYTHON_INCLUDE_FLAGS = \  
  2. -I/usr/include/python2.4  
  3. LIB_FLAGS = \  
  4. -lboost_python  
  5. SOURCE = \  
  6. hello_class.cpp  
  7. all:${SOURCE}  
  8. g++ ${PYTHON_INCLUDE_FLAGS} ${SOURCE} ${LIB_FLAGS} 
    -shared -o hello.so  
  9. clean:  
  10. rm -f hello *.o *.out *.so(3)hello_class.py  
  11. import hello  
  12. planet = hello.World()  
  13. planet.set('howdy')  
  14. planet.greet() 

以上就是對Python綁定C++程序的相關(guān)方法的介紹。


網(wǎng)頁標(biāo)題:Python綁定C++程序具體實(shí)現(xiàn)方法淺談
網(wǎng)站URL:http://uogjgqi.cn/article/cccedsd.html
掃二維碼與項目經(jīng)理溝通

我們在微信上24小時期待你的聲音

解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流