我可以将Cython模块静态链接到嵌入python的可执行文件中吗? [英] Can I statically link Cython modules into an executable which embeds python?

查看:118
本文介绍了我可以将Cython模块静态链接到嵌入python的可执行文件中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个从C ++编译并嵌入python的可执行文件。嵌入式可执行文件运行python脚本,该脚本加载了多个Cython模块。 Cython模块和可执行文件都链接到共享库。



我想通过将共享库与可执行文件静态链接来将共享库移入可执行文件。 / p>

我可以将Cython模块静态链接到嵌入python的可执行文件中吗?处理这种情况的最佳方法是什么?

解决方案

是可以的,但是如果您有使用python解释器的经验。我要描述的内容已在IOS平台上针对python完成。如果您不想接触原始的python解释器,则需要更多地了解如何让python知道您的模块(将TEST替换为您自己的标签/ libname)



一种可能的方法是:




  • 编译自己的带有dynload修补程序的Python ,它不希望对模块进行dlopen(),但直接使用dlsym()检查模块是否已在内存中。


  • 创建一个libTEST.a,包括在构建过程中生成的所有.o(而不是.so)。您通常可以在 build / temp。* 中找到它,然后执行以下操作:

      ar rc libTEST.a build / temp。* / *。o 
    ranlib libTEST.a


  • 在编译主可执行文件时,需要通过在编译命令行中附加以下内容来为该新libTEST.a添加依赖项:



    -lTEST -L。




结果将为您提供带有cython模块中所有符号的可执行文件,并且python将能够在内存中搜索它们。



(例如,我使用了增强的包装器,该包装器在编译过程中重定向ld而不产生.so并创建最后一个.a。在 kivy-ios 项目中,您可以抓取 liblink 用于生成.o和 biglink (用于获取目录中的所有.o并生成.a)。您可以在 build_kivy.sh )中查看其用法/ p>

I currently have an executable compiled from C++ that embeds python. The embedded executable runs a python script which load several Cython modules. Both the Cython modules and the executable are linked against a shared library.

I want to move the shared library into the executable by statically linking the shared library against the executable.

Can I statically link the Cython modules into the executable which embeds python? What is the best way to handle this situation?

解决方案

Yes it's possible, but if you have an hand on the python interpreter. What i'm going to describe have been done for python on IOS platform. You need to check more how to let python known about your module if you don't want to touch on the original python interpreter (Replace TEST everywhere with your own tag/libname)

One possible way to do it is:

  • Compile your own python with a dynload patch that prefer to not dlopen() your module, but use directly dlsym() to check if the module is already in memory.

  • Create an libTEST.a, including all the .o generated during the build process (not the .so). You can found it usually in the build/temp.*, and do something like this:

    ar rc libTEST.a build/temp.*/*.o
    ranlib libTEST.a
    

  • When compiling the main executable, you need to add a dependency to that new libTEST.a by appending in the compilation command line:

    -lTEST -L.

The result will give you an executable with all the symbol from your cython modules, and python will be able to search them in memory.

(As an example, I'm using an enhanced wrapper that redirect ld during compilation to not produce .so, and create a .a at the end. On the kivy-ios project, you can grab liblink that is used to produce .o, and biglink that is used to grab all the .o in directories and produce .a. You can see how it's used in build_kivy.sh)

这篇关于我可以将Cython模块静态链接到嵌入python的可执行文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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