本文介绍了将python编译到共享库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆python代码,我想将其编译为具有C接口的共享库,该接口可以与其他C / c ++程序链接,并且可以在不依赖太多其他库的情况下工作(也许python和某些其他dll,但它们都应包含在带有最终lib的目录中)。

I have a bunch of python code that I would like to "compile" into a shared library with a C interface that can be linked with other C/c++ programs and work without depending on too many other libs (perhaps python and some other dlls but they should all be included into a directory with the final lib).

我真的不想为此将python代码重写为C ++。我当然可以,但是最好有一个可以像dll / so lib这样使用的独立库。

I don't really want to rewrite the python code into C++ for this. I can of course, but it would be best to have a standalone lib that can be used like a dll/so lib.

我尝试了cython,想将python编译为C,然后将C代码编译为dll,但这似乎还行不通(我还没有能够使其完美运行)。然后我也尝试了bbfreeze-bbfreeze是否支持创建.so文件?无法找到具体方法。有人知道吗?

I have tried cython and wanted to compile python to C and then just compile C code into a dll but that doesn't seem to work quite yet (I haven't been able to make it work flawlessly yet). And then I also tried bbfreeze - but does bbfreeze support creating an .so file? Wasn't able to find out how to do it. Does anyone know?

您知道其他更简单的选择吗? python代码只需要编译一次。最好的办法是,如果它创建单个.so文件,则无论它有多大,只要没有太多依赖项就可以工作。

Do you know of any other options that are more straightforward? the python code only needs to be compiled once. And best of all would be if it creates a single .so file no matter how big it is that just works without too many dependencies.

推荐答案

您可以在C ++应用程序内部将Python用作库:它称为。

You can use Python as a library from inside your C++ application: it's called the Python/C API.

这个想法是您初始化自己的解释器,然后在其中加载脚本。您可以通过Python解释器内部的全局变量或模块来公开C ++对象,以便与您的代码进行交互。您可以直接从C ++代码直接运行Python函数。

The idea is that you initialize your own interpreter, then you load a script in it. You can expose your C++ objects through global variables or modules inside the Python interpreter for your code to interact with, your you can just run Python functions directly from your C++ code.

现在,我了解到您可能希望将Python脚本嵌入共享库中:使用传统的GNU工具链,这不一定是一件容易的事。有来实现,但是没有一个是官方的,而且似乎一切都太复杂了,而不是仅将脚本保存在外部文件中。

Now, I understand that you might want to have your Python scripts embedded inside the shared library: this is not necessarily an easy task, with the traditional GNU toolchain. There are multiple techniques to achieve this, but none is official, and all seem way too complicated as opposed to just having the script in an external file.

如果您的目标是向最终用户隐藏脚本,则可以对它们进行签名或使用私钥对它们进行加密,然后将公钥嵌入到您的库中,但是请记住,只要有足够的动力,任何人都可以轻松地检索到该密钥。

If your goal is to hide the scripts from the end-user, you could sign them or encrypt them with a private key and embed the public key inside your library, but keep in mind that the key can easily be retrieved by anyone with enough motivation.

这篇关于将python编译到共享库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:55
查看更多