如何将 Cython 生成的模块从 python 导入到 C/C++ 主文件?(C/C++编程)
How to import Cython-generated module from python to C/C++ main file? (programming in C/C++)
所以我有一个用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.dll
、 Fatal Python error: Py_Initialize: unable to load the file system codec
等错误。这个网站上有很多解决方案。
教程,这就是 Cython 用于通过编译的 C 模块扩展 Python 的方式。
- 单独的Cython模块是用Python编写的。Cython 会将其转换为静态编译模块,就像用 C 编写一样。
使用
setup.py
文件将Cython模块编译为*.so
共享库。这个共享库实际上是一个 Python 模块。python setup.py build_ext --inplace
从常规的Python脚本
import
Cython模块import helloworld
Cython通常用于用C扩展Python。另一方面,如果你想在你的C程序中嵌入Python代码,这也是可能的。看看关于将Python嵌入到C中的官方文档是一个先阅读的好地方。
这里有一个github项目解释了如何做到这一点,还有一个关于如何做到这一点的博客。
- 如何使用 samtools C API 构建一个简单的主.cpp文件
- VI工作室代码错误无法打开输出文件主.exe
- 如何正确定义C++类析构函数并将其链接到主文件?
- 头文件可以在主类中运行.这怎么可能?
- 如何从主.cpp中的cpp文件中获取功能结果?
- 链接外部C++外部C++ 在主文件中?
- 为什么我的主文件.cpp不打印头文件中的任何内容
- cpp 在主源文件中包括.cpp文件导致错误"duplicate symbol"
- 重定向输入和输出时如何处理主文件I/O?
- 当我从头文件和实现文件调用我的函数到我的主文件时,我没有得到任何输出
- 如何将 Cython 生成的模块从 python 导入到 C/C++ 主文件?(C/C++编程)
- 标题和INT主文件
- 关于 Linux .so 文件无法链接到主文件.cpp文件
- 如何在单个 Visual Studio 2010 项目中执行多个主文件
- 在C++中使用结构的头文件、初始化文件和主文件
- 从文件中读取矩阵,将其提供给主文件
- 如何使用 C++ 读取 NTFS 主文件表
- 如何在单独的cpp文件中通过头文件调用函数到主文件
- 将程序拆分为头文件和主文件
- 我的主C++文件中的文本(在尚未执行的代码中)如何显示在字符串中?