安装完Swig后,需要编辑两个文件,即example.i和example.cpp
其中example.i为:
%module example_vector
%include "std_string.i"
%include "std_vector.i"
%{
using namespace std;
vector<string> vector_int2str(vector<int> input);
%}
namespace std {
%template(StringVector) vector<string>;
%template(IntVector) vector<int>;
}
using namespace std;
vector<string> vector_int2str(vector<int> input);
其中example.cpp为:
#include <string>
#include <vector>
using namespace std;
vector<string> vector_int2str(vector<int> input) {
vector<string> result;
for (vector<int>::const_iterator it = input.begin();
it != input.end();
++it) {
result.push_back(to_string(*it));
}
return result;
}
生成后使用conda进入python2环境,以此执行下面的编译命令
swig -c++ -python example.i
g++ -fPIC -c example.cpp example_wrap.cxx -I/home/l/miniconda3/envs/python2/include/python2.7
g++ -shared example.o example_wrap.o -o _example_vector.so
其中-I/home/l/miniconda3/envs/python2/include/python2.7是python的安装目录,可以进入conda环境后使用下面的命令查找
python-config --cflags
本文详细介绍了如何安装Swig后编辑example.i和example.cpp文件,涉及模板、C++函数转换和Python接口。通过conda环境编译并生成Python模块,适合初学者了解C++与Python交互的技术流程。
1657

被折叠的 条评论
为什么被折叠?



