如何将Cython生成的模块从python导入C / C ++主文件? (用C / C ++编程) [英] How to import Cython-generated module from python to C/C++ main file? (programming in C/C++)

查看:193
本文介绍了如何将Cython生成的模块从python导入C / C ++主文件? (用C / C ++编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a function written in python and I followed the steps in Cython Documentation 'Building a Cython module using distutils'. However, it's unclear to me how to use that module that's working in python (by import it) to be embedded in C/C++ ? I just want to compile a C/C++ code that imports a python generated module using Cython (I guess it's a 2 step process)

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

*To clarify, I have already done all the steps and created an python module from a .pyx source file. But my question is how to integrate that module into an existing C/C++ file.

推荐答案

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

Just declare the stuff you want to call in c/c++ as cdef public

,例如:

# cymod.pyx
from datetime import datetime

cdef public void print_time():
    print(datetime.now().ctime())

当进行囊化时 cymod.pyx cymod.c ,也会生成一个 cymod.h

When cythonizing cymod.pyx to cymod.c, a cymod.h will be generated as well.

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

Then make a library, eg: cymod.lib (on windows).

在c代码中(main.c):

In the c codes(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)

Compile and run(main.exe)

注意::main.exe与python环境高度绑定,可能会遇到诸如找不到pythonxx.dll 致命的Python错误:Py_Initialize:无法加载文件系统编解码器。该网站上有很多解决方案。

Note: main.exe is highly bound to the python environments, one may run into errors such as cannot find pythonxx.dll, Fatal Python error: Py_Initialize: unable to load the file system codec. There are many solutions on this site.

这篇关于如何将Cython生成的模块从python导入C / C ++主文件? (用C / C ++编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆