如何将 Cython 生成的模块从 python 导入到 C/C++ 主文件?(C/C++编程)

How to import Cython-generated module from python to C/C++ main file? (programming in C/C++)

本文关键字:C++ 主文件 编程 导入 python Cython 模块      更新时间:2023-10-16

所以我有一个用python编写的函数,我按照Cython文档中的步骤"使用distutils构建Cython模块"。但是,我不清楚如何使用在 python 中工作的模块(通过导入它(嵌入到 C/C++ 中?我只想编译一个使用 Cython 导入 python 生成模块的 C/C++ 代码(我想这是一个 2 步过程(

*澄清一下,我已经完成了所有步骤并从 .pyx 源文件创建了一个 python 模块。但我的问题是如何将该模块集成到现有的 C/C++ 文件中。

只需将要在c/c ++中调用的内容声明为cdef public

例如:

# cymod.pyx
from datetime import datetime
cdef public void print_time():
    print(datetime.now().ctime())

cymod.pyx被细胞化为cymod.c时,也会生成一个cymod.h

然后创建一个库,例如:cymod.lib(在窗口上(。

在 c 代码 (main.c( 中:

#include "Python.h"
#include "cymod.h"

int main(int argc, char **argv)
{
Py_Initialize();  
PyInit_cymod();  // in cymod.h
print_time();    // call the function from cython
Py_Finalize();
return 0;
}

编译运行(主.exe(

注意:main.exe 与 python 环境高度绑定,可能会遇到 cannot find pythonxx.dllFatal Python error: Py_Initialize: unable to load the file system codec 等错误。这个网站上有很多解决方案。

通过查看 Cython

教程,这就是 Cython 用于通过编译的 C 模块扩展 Python 的方式。

  1. 单独的Cython模块是用Python编写的。Cython 会将其转换为静态编译模块,就像用 C 编写一样。
  2. 使用setup.py文件将Cython模块编译为*.so共享库。这个共享库实际上是一个 Python 模块。

    python setup.py build_ext --inplace

  3. 从常规的Python脚本import Cython模块

    import helloworld

Cython通常用于用C扩展Python。另一方面,如果你想在你的C程序中嵌入Python代码,这也是可能的。看看关于将Python嵌入到C中的官方文档是一个先阅读的好地方。

这里有一个github项目解释了如何做到这一点,还有一个关于如何做到这一点的博客。