1. 使用sudo apt install swig来按照swig
2. 编写对应的.i文件
假设我们编写的c++文件和.h文件如下:
/* File: example.cpp */
#include "example.h"
int fact(int n) {
if (n < 0){ /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
}
else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}
/* File: example.h */
int fact(int n);
则对应的.i文件如下:
/* File: example.i */
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
int fact(int n);
3. 生成对应的.example_wrap.cxx和example.py.
运行命令:swig -c++ -python example.i
4. 使用 distutils工具编译
首先生成一个setup.py文件
#!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.cxx', 'example.cpp'], #一定要把cpp源文件包含,如果该源文件包含了别的依赖,则应该也包含进来
)
setup (name = 'example',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)
然后使用命令python setup.py install编译生成即可