1.安装Swig
- 下载Swig源码包 http://www.swig.org/survey.html
- 解压后执行 ./configure
- make && make install
2.准备C/C++文件
1.新建cal.h
int add(int a, int b);
int sub(int a, int b);
2.新建cal.cpp
int add(int a, int b){
return a+b;
}
int sub(int a, int b){
return a-b;
}
3.通过C/C++文件生成py文件
1.新建cal.i
%module cal
%{
#define SWIG_WITH_INIT
#include "cal.h"
%}
%include "cal.h"
2.在终端输入swig -python -c++ cal.i
生成cal_wrap.cxx和cal.py
3.新建setup.py文件
from distutils.core import setup
from distutils.core import Extension
test_module = Extension(name = '_cal',
sources = ['cal_wrap.cxx','cal.cpp'],
)
setup(name = 'cal_package',
version = '1.0',
author = 'Mightypants',
ext_modules = [test_module],
py_modules = ['cal'],
)
4.在终端输入python setup.py build
,等待编译完成
4.测试生成的py文件
1.新建测试文件test_cal.py
import cal
print(cal.sub(3,2))
2.将build/lib.linux-x86_64-2.7/
路径下的cal.py
与_cal.so
文件复制到test_cal.py
文件目录下,在终端输入python test_cal.py
即可测试结果