最快的方法是使用
SWIG
SWIG的示例
tutorial
:
/* File : example.c */
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern int fact(int n);
%}
extern int fact(int n);
在Unix上构建Python模块:
swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so
用法:
>>> import example
>>> example.fact(5)
120
请注意,必须使用python-dev。在某些系统中,python头文件将基于安装方式位于/usr/include/python2.7中。
从教程中:
SWIG是一个相当完整的C++编译器,支持几乎所有的语言特征。这包括预处理、指针、类、继承,甚至C++模板。SWIG还可以用于在目标语言中将结构和类打包成代理类,以非常自然的方式公开底层功能。