2012年5月17日

swig - 讓python使用C/C++模組

試了boost.python建立.dll/.pyd檔,一直有版本問題,所幸來試試swig


下載swig
http://www.swig.org/

下載安裝perl compatible regular expressions (optional)
http://www.pcre.org/

#install pcre on mac cd pcre ./configure --prefix=/usr --disable-static --libdir=/lib \ --docdir=/usr/share/doc/pcre-8.30 --enable-utf8 \ --enable-unicode-properties \ --enable-pcregrep-libz --enable-pcregrep-libbz2 && make  make install 指令說明參考http://www.linuxfromscratch.org/blfs/view/svn/general/pcre.html

安裝swig

./configure make make install and you are ready to go!

我們先來試試看官網的範例
http://www.swig.org/Doc1.3/Python.html

假設我們有example.h和example.cpp
/* File: example.cpp */ #include "example.h" int fact(int n) { if (n < 0){ /* This should probably return an error, but this is simpler */ return 0; } if (n == 0) { return 1; } else { /* testing for overflow would be a good idea here */ return n * fact(n-1); } } int add(int n, int m){ return n + m; } example.h
/* File: example.h */ int fact(int n); int add(int n, int m);

建立一個中介擋example.i

/* File: example.i */ %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} int fact(int n); int add(int n, int m);

接著我們想使用distutils來幫我們檢查內容並且產生正確的object file或DLL(.so or .pyd)
我們先建立一個setup.py #!/usr/bin/env python """ setup.py file for SWIG example """ from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.cxx', 'example.cpp'], ) setup (name = 'example', version = '0.1', author = "flyakite", description = """Simple swig example from docs""", ext_modules = [example_module], py_modules = ["example"], )

接下來使用指令 swig -c++ -python example.i python setup.py build_ext --inplace 就完成嚕 python >>>import example >>>example.add(1,2) 3 >>>example.fact(4) 24