#python和C/C++#讓python和C/C++聯姻

來源:互聯網
上載者:User

讓python不在孤單,輕易而舉的為python寫C/C++第三方庫。

我們都知道python很慢,特別是處理大資料的時候,簡直慢到極致,如果在知道代碼的瓶頸的時候,可以將需要大量計算的資料區塊放在C/C++代碼裡運算,然後再將資料返回給python。對,這也讓python易於擴充,這樣我們可以將大部分時間放在核心的代碼上。

在看過一些複雜的調用方式之後,總覺得上手不易,麻煩,細想,這完全與python的simple is better哲理違背啊,果斷放棄。這幾天在深圳先進研究院做項目的時候,用到了QT,然後無意中發現了SIP。官方解釋是SIP is a tool for automatically generating Python bindings for C and C++ libraries(還是用原文比較好,翻譯之後總覺得變味了)。起初,SIP是為了PyQt而建,不過也能為其他C/C++庫產生python的代碼。

就此,發現了讓python調用C/C++代碼的利器。這樣我們就可以遊刃有餘的穿梭在python和C/C++代碼之間了。It’s perfect。有時細想,python開發的高速度加上C/C++啟動並執行高速度,能讓JAVA汗顏了吧。不過,企業承認JAVA的穩定性還是NO.1的,我也不敢亂加評價。

那好,我們開始SIP之旅吧。

下面我是在windows下的配置,不過我沒有用windows下預設的編譯器,因為我發現中途遇見了各種問題,徹底讓我心碎了,所以我用了mingw32.

第一步:配置環境

  • 下載mingw32
  • 下載SIP
  • 下載gunmake,在windows下運行make還需要libintl, libiconv.
最重要的是,分別將mingw32,make等bin目錄放在PATH下,否則找不到make,g++等命令。

第二步:安裝SIP

切換到SIP的根目錄下,運行

python configure.py --platform win32-g++

指定SIP在C/C++代碼時,是使用mingw32版本的編譯器。

然後執行

makemake install

大功告成。

第三步:讓C/C++跑起來吧

建立3個檔案。

configure.py   mymath.cpp   mymath.h   mymath.sip

內容分別是:
configure.py

view plaincopy to clipboardprint?
  1. import os  
  2. import sipconfig  
  3.   
  4. # The name of the SIP build file generated by SIP and used by the build  
  5. # system.  
  6. build_file = "mymath.sbf"  
  7.   
  8. # Get the SIP configuration information.  
  9. config = sipconfig.Configuration()  
  10.   
  11. # Run SIP to generate the code.  
  12. cmd = " ".join([config.sip_bin, "-c", ".", "-b", build_file, "mymath.sip"])  
  13. os.system(cmd)  
  14.   
  15. # Create the Makefile.  
  16. makefile = sipconfig.SIPModuleMakefile(config, build_file)  
  17.   
  18. # Add the library we are wrapping.  The name doesn't include any platform  
  19. # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the  
  20. # ".dll" extension on Windows).  
  21. makefile.extra_libs = ["mymath"]  
  22. makefile.LIBDIR.append("./")  
  23.   
  24. # Generate the Makefile itself.  
  25. makefile.generate()  

mymath.h

view plaincopy to clipboardprint?
  1. /* 
  2. define my own math library 
  3. */  
  4.   
  5. class MyMath{  
  6.   
  7. public:  
  8.     int Add(int a, int b);  
  9.     int Minus(int a, int b);  
  10. };  

mymath.cpp

view plaincopy to clipboardprint?
  1. #include "mymath.h"  
  2.   
  3. int MyMath::Add(int a, int b)  
  4. {  
  5.     return a + b;  
  6. }  
  7.   
  8. int MyMath::Minus(int a, int b)  
  9. {  
  10.     return a - b;  
  11. }  

mymath.sip

view plaincopy to clipboardprint?
  1. // Define the SIP wrapper to the word library.  
  2.   
  3. %Module MyMath  
  4.   
  5. class MyMath {  
  6.   
  7. %TypeHeaderCode  
  8. #include "mymath.h"  
  9. %End  
  10.   
  11. public:  
  12.     int Add(int a, int b);  
  13.     int Minus(int a, int b);  
  14. };  

執行檔案下的configure.py,你可以看到產生以下檔案:

mymath.sbf  sipAPIMyMath.h   sipMyMathcmodule.cpp  sipMyMathMyMath.cpp  Makefile

可以看看makefile檔案的內容。

在這裡需要產生mymath的靜態連結庫,用以下命令:

g++ -c mymath.cpp  ----->產生objective file,mymath.oar cr mymath.lib mymath.o   ----->產生靜態連結庫mymath.lib

到此,離成功還有半步距離了。
然後再執行make,即產生MyMath.pyd,如果你想安裝MyMath.pyd,則make install即可。

我們來看看我們擴充的C/C++庫吧。

>>> import MyMath>>> dir(MyMath)['MyMath', '__doc__', '__file__', '__name__', '__package__']>>> s = MyMath.MyMath()>>> dir(s)['Add', 'Minus', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']>>> s.Add(1, 2)3

好,白楊到此一遊。Enjoy it。具體內容請詳看相應的參考檔案。

 

-----------------打造高品質的文章 更多關注 把酒泯恩仇---------------

為了打造高品質的文章,請  推薦  一個吧。。。。謝謝了,我會寫更多的好文章的。

請關注sina微博:http://weibo.com/baiyang26

把酒泯恩仇官方部落格:http://www.ibaiyang.org 【推薦用google reader訂閱】

把酒泯恩仇官方豆瓣:http://www.douban.com/people/baiyang26/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.