这是一个使用 SWIG 的示例:
调用C++函数“inflow”的Python代码:
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++ 代码的名称与之前的名称不同
命令中给出。否则它将被 swig 代码覆盖。
假设 example_wrap.cpp 是您要与 Python 交互的文件,“example.i”是 SWIG 接口文件。 SWIG 将生成一个名为 example.cpp 的新文件。
2) swig -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.o
想法是编译后的模块名称应该以下划线开头,后跟名称。
5) 在term中打开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"