1 cython
C语言可以调用python
编写c.pyx文件
cdef public c_func(const char *str):
print(str)
cython编译
编译:cython c.pyx
生成文件c.c和c.h
c.h
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initc(void);
#else
PyMODINIT_FUNC PyInit_c(void);
#endif
#endif /* !__PYX_HAVE__c */
c调用python函数
c_py.c
#include<Python.h>
#include"c.h"
int main(int argc,char *argv[])
{
Py_Initialize();
initc();
c_func("hello python\n");
Py_Finalize();
}
编译:gcc c_py.c c.c -o c_py -I/usr/include/python2.7/ -lpython2.7
执行输出: hello python
2 SWIG
python 调用C
编写.i文件
/* swig.i*/
%module swig
%{
void python()
{
printf("hello python\n");
}
%}
void python();
swig进行编译
swig -python swig.i
生成swig_wrap.c和swig.py
编译成python扩展
gcc -fPIC -shared swig_wrap.c -o _swig.so -I/usr/include/python2.7/ -lpython2.7
调用执行
import swig即可以使用