【问题标题】:use cython to build multiple python modules into a program [duplicate]使用cython将多个python模块构建到一个程序中[重复]
【发布时间】:2019-04-06 12:14:47
【问题描述】:

我有一个由一个主程序和一个或多个支持模块组成的 python 程序(可能带有 cython 扩展)。

我知道可以使用 cython 将每个模块构建到它自己的 so 和 main program into an executable

但是我想做的是将程序和它的支持模块构建到一个可执行文件中。 Linux 上的 cython 可以做到这一点吗?

【问题讨论】:

    标签: linux cython


    【解决方案1】:

    是的,这是可能的,但需要一点技巧。

    首先让我们考虑一下我们的主程序和一个支持库

    cythontest.pyx:

    cpdef int square(int n):
    return n * n
    

    cythontestmain.pyx

    import cythontest
    print(cythontest.square(100))
    

    让我们构建它:

    cython3 --embed cythontestmain.pyx
    cython3 cythontest.pyx
    gcc -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5m -o cythontestmain cythontestmain.c cythontest.c -lpython3.5m
    

    不幸的是,这不起作用。加载程序找不到模块。幸运的是,可以通过在 cythontestmain.pyx 顶部添加几行来手动加载它

    cdef extern void * PyInit_cythontest()
    PyInit_cythontest()
    

    (void * 的返回类型并不严格正确,但由于我们无论如何都会丢弃返回值,因此在实践中不太可能成为问题。

    我们现在可以成功构建和运行程序了。

    【讨论】:

    • 你应该将它声明为cdef extern object PyInit_cythontest(),然后Cython会自动检查并处理可能的错误。
    猜你喜欢
    • 2018-06-21
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2023-01-15
    • 1970-01-01
    相关资源
    最近更新 更多