因此,我有一个用 python 编写的函数,并且按照 Cython 文档“使用 distutils 构建 Cython 模块”中的步骤进行操作。但是,我不清楚如何使用在 python 中工作的模块(通过导入它)嵌入到 C/C++ 中?我只想编译一个 C/C++ 代码,使用 Cython 导入 python 生成的模块(我猜这是一个 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
to cymod.c
, a cymod.h
也会生成。
然后创建一个库,例如:cymod.lib
(在 Windows 上)。
在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;
}
编译并运行(main.exe)
Note:main.exe 与 python 环境高度绑定,可能会遇到以下错误cannot find pythonxx.dll
, Fatal Python error: Py_Initialize: unable to load the file system codec
。这个网站上有很多解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)