標籤:
SIP 是為Python產生C++介面代碼的工具,它與 SWIG 類似,但使用不同的介面格式。其思想起源於SWIG,主要是為將QT封裝為Python創造,它用作建立 PyQt和 PyKDE ,並支援 Qt signal/slot 系統。
本文主要介紹在Window平台下,SIP的編譯、安裝,以及將C++代碼產生為Python。本文是在安裝了Python的前提下介紹,Python的安裝包,可以上其官網下載,這裡不再累贅!
1.SIP編譯及安裝
在SIP官網http://www.riverbankcomputing.com/software/sip/download下載SIP,其最新版本是4.16.7,我下載的是最新版本。解壓SIP,開啟Windows的cmd命令列,進入SIP根目錄,輸入python configure.py --show-platform查看支援的平台。4.16.7支援的平台如下:
從上面可以看出,SIP目前還不支援VS2012,但開啟SIP根目錄下的specs查看所支援的平台時發現,可以通過修改其平台設定檔做到支援VS2012。
將win32-msvc2010複製一份,將複製一份名稱修改為win32-msvc2012,用文字編輯器開啟win32-msvc2012,修改一下內容:
將QMAKE_COMPILER_DEFINES += _MSC_VER=1600 WIN32修改為QMAKE_COMPILER_DEFINES += _MSC_VER=1700 WIN32
將QMAKE_CFLAGS = -nologo -Zm200 -Zc:wchar_t-修改為QMAKE_CFLAGS = -nologo -Zm200 -Zc:wchar_t
回到SIP根,用文字編輯器開啟configure.py將下面紅色標註的內容替換為win32-msvc2012:
現在SIP支援VS2012了!
開啟VS2012 開發人員命令提示,進入SIP根目錄,依次執行以下命令:
python configure.py --platform win32-msvc2012
nmake
nmake install
第一條語句主要是產生Makefile檔案
2.C++->Python
1)利用VS建立一個靜態庫的工程,主要實現字串逆序,其內容如下:
.h檔案
#ifndef PYSIPTEST_INCLUDE_H#define PYSIPTEST_INCLUDE_H#include <string>using namespace std;class Word {private:const string the_word;public:Word(const char *w) : the_word(w) {};const char* Reverse() const;};#endifCPP檔案
#include <string>#include <algorithm>#include "PySIPTest.h"const char* Word::Reverse() const{string strTemp = the_word;std::reverse(strTemp.begin(), strTemp.end());return strTemp.c_str();}
2)編寫configure.py檔案和*.sip檔案
<span style="font-size:18px;">// word.sip%Module wordclass Word {%TypeHeaderCode#include <string>#include <word.h>%End public: Word(const char* w); const char* reverse() const;};# configure.pyimport os, sipconfig, sys# The name of the SIP build file generated by SIP and used by the build system.build_file = "word.sbf"# Get the SIP configuration information.# Documentation: http://pyqt.sourceforge.net/Docs/sip4/build_system.htmlconfig = sipconfig.Configuration()# Run SIP to generate the code.cmd = " ".join([config.sip_bin, "-c", ".", "-b", build_file, "word.sip"])print( "running command " + cmd )os.system(cmd)# Create the Makefile.makefile = sipconfig.SIPModuleMakefile(config, build_file)# Add the library we are wrapping.# The name doesn't include any platform specific prefixes or extensions.makefile.extra_libs = ["word"]# Generate the Makefile itself.makefile.generate()</span>
運行configure.py,會產生一個makefile檔案(直接用IDLE開啟configure.py,按F5運行;或者命令列用python configure.py運行都可以)
執行nmake命令產生,nmake install 安裝。
這樣C++就會封裝為Python,如果沒有設定目錄,就會安裝預設Python目錄\Lib\site-packages下。
3.運行
開啟Python 的命令列,進行測試:
Python 2.X系列測試代碼如下:
<span style="font-size:18px;">import wordword.Word("SIPTest").reverse()</span>
Python 3.x系列測試代碼如下:
<span style="font-size:18px;">import wordword.Word(b"SIPTest").reverse()</span>
SIP很是強大,本文只是膚淺的介紹了SIP的一點東西,歡迎大家指正。
同時歡迎大家轉載,轉載請註明出處!
利用SIP將C++封裝為Python