下面是使用SWIG一個例子:
的Python代碼它調用C++函數 「流入」:
import inflow # importing C++ inflow library
nframes = 25
print 'calling inflow function in loop ...'
for i in xrange(0,1001):
z = inflow.inflow(""" arguments""")
""" code does something with z """
的C++函數將照常:
#include <iostream>
#include <vector>
inflow(/* arguments from Python*/)
{
/* code does something */
}
我們接口與Python,這裏的步驟:
1)重要 - 確保C++代碼y在此步驟中試圖綁定的名稱與命令中給出的 不同。否則它會被swig代碼覆蓋。
比方說example_wrap.cpp是你想用Python和「example.i」接口的文件是SWIG接口文件。 SWIG將生成一個名爲example.cpp的新文件。
2)痛飲-C++ -python -o example_wrap.cpp example.i
3)的g ++ -I /usr/include/python2.7 -fPIC -c example_wrap.cpp -o example_wrap.o
4)g ++ -shared -o _example.so example_wrap。
想法是編譯的模塊名稱應該以下劃線開頭,後面跟着名稱。
5)打開Python的足月,並說
from example import *
,然後開始呼叫的功能。
6)來源:http://www.iram.fr/~roche/code/python/SWIG.html#purpose
該示例的接口文件看起來是這樣的:
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
// Instantiate templates used by example
namespace std {
%template(IntVector) vector<int>;
%template(DoubleVector) vector<double>;
}
// Include the header file with above prototypes
%include "example.h"
您是否考慮過SWIG接口生成器? http://www.swig.org/ IT將C/C++代碼作爲.so文件包裝爲Python代碼,您可以直接從Py調用這些C/C++函數。 – atmaere