C语言利用Cython调用Python
1. 安装cython
sudo apt-get install cython
2. 修改py文件
首先把Infrared.py文件的后缀改成Infrared.pyx,然后进入.pyx文件进行修改。只需要修改导出的函数,并且形参不能设置默认值(例如arg=1是不行的)。修改方法是把def 改成cdef,并且在cdef后紧跟public。
在顶部加上下面这句注释,就没有警告了, # 也需要
# cython:language_level=3
3. python转.c和.h
使用cython的命令进行转换
cython Infrared.pyx
4. 书写main.c文件
这一步是main.c去调用Python生成的c文件导出的那个函数。用箭头指出的名字都是要特别注意的,是要和文件名相同的
#include "Python.h"
#include "Infrared.h"
#include <stdio.h>
int main(int argc, char **argv) {
int status=PyImport_AppendInittab("Infrared", PyInit_Infrared);
if(status==-1){
return -1;//error
}
Py_Initialize();
PyObject *module = PyImport_ImportModule("Infrared");
if(module==NULL){
Py_Finalize();
return -1;//error
}
PyObject *binfile;
PyObject *output;
PyObject *threshold_seg;
binfile = Py_BuildValue("s", "./testdata/20221126-1-2.bin");
output = Py_BuildValue("s", "./output/");
threshold_seg = Py_BuildValue("f", 0.5);
printf("start...\n");
Infrared_Imaging_Enhancing(binfile, output,threshold_seg);
Py_Finalize();
return 0;
}
5. 执行gcc命令编译
-同时编译main.c和Infrared.c, -o是输出名字,-I指定的目录是寻找头文件的目录,-l指定寻找的库文件(大写L指定目录),
gcc main.c Infrared.c -o main -I/usr/include/python3.8/ -lpython3.8