简体   繁体   中英

Compiling python into a shared library

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).

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.

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?

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.

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

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.

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更多地设置为以相反的方式工作:您的代码是从Python调用的,整体逻辑在Python中,而特定于问题(和性能关键代码)是用C / C ++编写的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM