SWIG 的应用(一)

用 C/C++ 扩展 Python。

- 如果仅使用标准 C 库函数,则可以使用 Python 自带的 ctypes 模块,或者使用 cffi。

- 如果要使用自定义 C/C++ 函数,又不怕写 wrapper 麻烦,则可以使用 Python C API。

- 如果专门针对 C++ 模块打包,可以尝试使用 Boost。

除此之外,可以尝试一下 SWIG 打包 C/C++,以下是一个开始。

1) 自己编写接口文件 *.i

要打包的 C 代码 firstSwig.c

/* File: first swig, c file. */

double my_ver = 0.1;

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

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

定义接口文件 firstSwig.i

/* swig interface file */

%module firstSwig

%{
// Put headers and other declarations here
extern double my_ver;
extern int    fact(int);
extern int    mod(int, int);
%}

extern double my_ver;
extern int    fact(int);
extern int    mod(int, int);

swig 命令生成 wrapper 文件 firstSwig_wrap.c 和 Python 模块文件 firstSwig.py

$ swig -python firstSwig.i

gcc 编译生成目标文件 firstSwig.ofirstSwig_wrap.o

$ gcc -c -fpic firstSwig.c firstSwig_wrap.c -I /usr/include/python2.7/

gcc 链接目标文件为动态链接库 _firstSwig.so

$ gcc -shared firstSwig.o firstSwig_wrap.o -o _firstSwig.so

然后将 firstSwig.py_firstSwig.so 一起发布即可。

2) 不编写接口文件 *.i,而是直接用头文件 *.h  (注意这种情况下,不支持变量的打包)

要打包的 C 代码 firstSwig.c

/* File: first swig, c file. */

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

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

对应 C 代码的头文件 firstSwig.h

/* File: first swig, header file. */

// factorial
int fact(int n);

// mod
int mod(int m, int n);

swig 直接使用头文件生成 wrapper 文件 firstSwig_wrap.c 和 Python 模块文件 firstSwig.py

$ swig -python -module firstSwig firstSwig.h

其余步骤和方法 1) 一致,

gcc 编译生成目标文件 firstSwig.ofirstSwig_wrap.o

$ gcc -c -fpic firstSwig.c firstSwig_wrap.c -I /usr/include/python2.7/

gcc 链接目标文件为动态链接库 _firstSwig.so

$ gcc -shared firstSwig.o firstSwig_wrap.o -o _firstSwig.so

然后将 firstSwig.py_firstSwig.so 一起发布即可。

完。

原文地址:https://www.cnblogs.com/gaowengang/p/8576310.html