当前位置:   article > 正文

利用Cython把python转c_cython将python转为c代码

cython将python转为c代码

1. 安装cython

sudo apt-get install cython
  • 1

2. 修改py文件

首先把Infrared.py文件的后缀改成Infrared.pyx,然后进入.pyx文件进行修改。只需要修改导出的函数,并且形参不能设置默认值(例如arg=1是不行的)。修改方法是把def 改成cdef,并且在cdef后紧跟public
在这里插入图片描述

在顶部加上下面这句注释,就没有警告了, # 也需要

# cython:language_level=3
  • 1

3. python转.c和.h

使用cython的命令进行转换

cython Infrared.pyx
  • 1

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

5. 执行gcc命令编译

-同时编译main.c和Infrared.c, -o是输出名字,-I指定的目录是寻找头文件的目录,-l指定寻找的库文件(大写L指定目录),

gcc main.c Infrared.c -o main -I/usr/include/python3.8/ -lpython3.8
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/748366
推荐阅读
相关标签
  

闽ICP备14008679号