我从Python & lt;-& gt;C++绑定开始这个页面,目的是链接高级数据类型(多维STL向量和Python列表):
尝试了基于两者的解决方案
ctypes
boost.python
(而且不是软件工程师)我发现当需要高级数据类型绑定时它们很复杂,而我发现
SWIG
因此,这个例子使用SWIG,并且已经在Linux中进行了测试(但是SWIG是可用的,并且在Windows中也被广泛使用)。
目的是使一个C++函数可用于Python,该函数采用一个2D STL向量形式的矩阵,并返回每行的平均值(作为1D STL向量)。
#include <vector>
#include "code.h"
using namespace std;
vector<double> average (vector< vector<double> > i_matrix) {
// Compute average of each row..
vector <double> averages;
for (int r = 0; r < i_matrix.size(); r++){
double rsum = 0.0;
double ncols= i_matrix[r].size();
for (int c = 0; c< i_matrix[r].size(); c++){
rsum += i_matrix[r][c];
}
averages.push_back(rsum/ncols);
}
return averages;
}
等效标题(“code.h”)为:
#ifndef _code
#define _code
#include <vector>
std::vector<double> average (std::vector< std::vector<double> > i_matrix);
#endif
我们首先编译C++代码来创建一个对象文件:
g++ -c -fPIC code.cpp
然后我们定义
SWIG interface definition file
%module code
%{
#include "code.h"
%}
%include "std_vector.i"
namespace std {
/* On a side note, the names VecDouble and VecVecdouble can be changed, but the order of first the inner vector matters! */
%template(VecDouble) vector<double>;
%template(VecVecdouble) vector< vector<double> >;
}
%include "code.h"
使用SWIG,我们从SWIG接口定义文件生成C++接口源代码。
swig -c++ -python code.i
g++ -c -fPIC code_wrap.cxx -I/usr/include/python2.7 -I/usr/lib/python2.7
g++ -shared -Wl,-soname,_code.so -o _code.so code.o code_wrap.o
我们现在可以在Python脚本中使用该函数:
#!/usr/bin/env python
import code
a= [[3,5,7],[8,10,12]]
print a
b = code.average(a)
print "Assignment done"
print a
print b