前言:
swig可以實現(xiàn)多種高級語言(如python,R,Java等)對C/C++的使用,提供一種轉(zhuǎn)換的接口.這里由于項目的需要,介紹下Python對C++的支持.(本文部分參考其它網(wǎng)絡(luò)文章,但代碼均經(jīng)過驗證可行)
安裝SWIG(ubuntu 14.04):
- 1.安裝pcre(pcre提供對正則表達(dá)式的支持)
sudo apt-get update
sudo apt-get install libpcre3 libpcre3-dev
可能還需要安裝:
sudo apt-get install openssl libssl-dev
- 2.安裝SWIG:
sudo apt-get install swig
安裝結(jié)束
簡單使用
- 1.用c++語言編寫頭文件和源文件為:
頭文件example.h:
int fact(int n);
源文件example.cpp:
#include "example.h"
int fact(int n){
if(n<0){
return 0;
}
if(n==0){
return 1;
}
else{
return (1+n)*fact(n-1);
}
}
- 2.寫swig模塊寫一個文件example.i:
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
int fact(int n);
- 3.使用swig生產(chǎn)cxx文件,建python模塊:
swig -c++ -python example.i
執(zhí)行完命令后會生成兩個不同的文件:example_wrap.cxx和example.py.
- 4.最后一步,利用python自帶工具distutils生成動態(tài)庫:
python自帶一個distutils工具,可以用它來創(chuàng)建python的擴(kuò)展模塊.
要使用它,必須先定義一個配置文件,通常是命名為setup.py
"""
setup.py
"""
from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.cxx','example.cpp'],
)
setup (name='example',
version='0.1',
author="SWIG Docs",
description="""Simple swig example from docs""",
ext_modules=[example_module],
py_modules=["example"],
)
注意:頭文件和源文件都是example.*,那么setup.py腳本中Extension的參數(shù)必須為"_example"
- 5.編譯
python setup.py build_ext --inplace
- 6.測試
python命令行:
>>>import example
>>>example.fact(4)
24
>>>
*7.支持STL
*7.1. vector
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include stl.i
namespace std{
%template(VectorOfString) vector<string>;
}
int fact(int n);
std::vector<std::string> getname(int n);
*7.2. vector<vector<> >
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include stl.i
namespace std{
%template(stringvector) vector<string>;
%template(stringmat) vector<vector<string> >;
}
int fact(int n);
std::vector<std::vector<std::string> > getname(int n);
*7.3. vector<vector<struct> >二維vector(多維vector定義+struct)
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include stl.i
struct point
{
int i;
int j;
};
namespace std{
%template(stringvector) std::vector<point>;
%template(stringmat) std::vector<std::vector<point> >;
}
std::vector<std::vector<point> > getname(int n);
/*結(jié)束
namespace std塊中,第一個vector是第二個vector的基礎(chǔ),也就是第一個是第二個的子集,需要先申明內(nèi)部,然后才能定義更加復(fù)雜的部分,比如我之前只定義了如下的namespace std形式:
namespace std{
%template(stringvector) std::vector<double>;
%template(stringmat) std::vector<std::vector<point> >;
}
尋找了好長時間也沒找到錯誤的原因,后來查閱外文資料,才知道這個必須要逐個聲明,也就是這里,它不知道std::vector<point>是怎么來的,所以我必須要先聲明std::vector<point>才行,即上文形式,這個問題困擾了我好長時間,現(xiàn)在終于解決了.
*/