SWIG, Simplified Wrapper and Interface Generator, It's a software development tool , It will C and C++ The program is connected with various high-level programming languages .SWIG Available for different types of target languages , Including common scripting languages , Such as Javascript、Perl、PHP、Python、Tcl and Ruby. The list of supported languages also includes non scripting languages , Such as C#,D,Go language,Java, Include Android,Lua,OCaml,Octave,Scilab and R. It also supports several kinds of interpretation and compilation Scheme Realization (Guile,MzScheme/Racket)
agt-get install swig
usage
1. establish C Files and header files
example.c
#include "example.h" int fact(int n) { if (n < 0) { return 0; } if (n == 0) { return 1; } else { return n * fact(n-1); } }
example.h
int fact(int n);
2. To write swig Interface file example.i
%module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} int fact(int n)
- %module The following name is the name of the encapsulated module ,Python Load the program by this name .
- %{…%} Added between , It generally contains some function declarations and header files required by this file .
- Last part , Declare the functions and variables to be encapsulated .
swig The simplicity of the interface file is that it is easy to write
3. Call... Using the command line Swig Methods produce Python modular
swig -python example.i
It will be generated after execution 2 New file :example_wrap.c,example.py
4. use setup.py Generate so file
setup.py
from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.cpp'], ) setup(name='example', version='0.1', author="SWIG Docs", description="""Simple swig example from docs""", ext_modules=[example_module], py_modules=["example"], )
Derived .so File naming needs to start with an underscore _
Compile the generated so file
python setup.py build_ext --inplace
5. stay C Call in language program
test.py
import _example print(_example.fact(4))