SWIG打包C代码为so文件

cooolr 于 2021-08-07 发布

安装命令

sudo apt install swig python3-dev

C file

/* File : example.c */

double  My_variable  = 3.0;

/* Compute factorial of n */
int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
  return(n % m);
}

SWIG interface file

/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);

打包命令

unix> swig -python example.i
unix> gcc -c -fpic example.c example_wrap.c -I/home/pi/anaconda3/include/python3.7m
unix> gcc -shared example.o example_wrap.o -o _example.so

Python调用

unix> python
Python 3.7...
>>> **import _example**
>>> **_example.fact(4)**