功能目的:用c++写一个功能,然后用swig将c++写得功能封装成一个python库,然后在python中可以直接import 调用。
注:SWIG 实际上是一个编译器,获取C/C++的声明,用一个壳包起来,以便通过其他语言访问这些声明。因此,SWIG 最大的好处就是将脚本语言的开发效率和 C/C++ 的运行效率结合起来。
1.安装 swig
sudo apt-get install swig
输入:swig -version
查看是否安装成功,成功会出现:
SWIG Version 3.0.12
Compiled with g++ [x86_64-pc-linux-gnu]
Configured options: +pcre
Please see http://www.swig.org for reporting bugs and further information
2.写一个c++头文件 example.h
#include <iostream>
using namespace std;
class Example{
public:
void say_hello();
};
3.写个c++源文件example.cpp,对头文件中的方法进行实现
#include "example.h"
void Example::say_hello(){
cout<<"hello"<<endl;
}
4.写一个".i"文件example.i,将c++写得功能方法打包成扁平的接口
%module example
%{
#include "example.h"
%}
%include "example.h"
a.%module后面的名字是被封装的模块名称,Python通过这个名称加载程序。
b.%{…%}之间所添加的