代码之家  ›  专栏  ›  技术社区  ›  plugwash

使用cython将多个python模块构建到一个程序中

  •  0
  • plugwash  · 技术社区  · 7 年前

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

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

    然而,我想做的是将程序及其支持模块构建成一个可执行文件。在Linux上使用cython有可能吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   plugwash    7 年前

    是的,这是可能的,但需要一些黑客技术。

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

    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*的返回类型不是严格正确的,但由于我们无论如何都要丢弃返回值,所以在实践中不太可能出现问题)。

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

    推荐文章