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, which can be linked to other C / C ++ programs and work regardless of too many other libs (maybe python and some other dlls, but they should all be included in the directory with the final lib).

I really don't want to rewrite Python code in C ++ for this. I can, of course, but it would be better to have a standalone lib that can be used as dll / so lib.

I tried cython and wanted to compile python to C and then just compile the C code into dll, but that still doesn't work (I haven't been able to make it work flawlessly yet). And then I also tried bbfreeze - but does bbfreeze support creating a .so file? Could not figure out how to do this. Somebody knows?

Do you know any other options that are simpler? python code needs to be compiled only once. And it would be best if he created one .so file no matter how large it is, it just works without too many dependencies.

+4
source share
2 answers

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

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

Now I understand that you might want your Python scripts to be embedded in a shared library: this is not necessarily an easy task with traditional GNU tools. There are several methods to achieve this, but none of them are official, and all this seems too complicated, not just a script in an external file.

If your goal is to hide scripts from the end user, you can sign them or encrypt them using the private key and insert the public key inside your library, but keep in mind that the key can be easily extracted by someone with sufficient motivation.

0
source

Python is more tuned to work in a different way: your code is called from Python, the general logic is in Python, while the task-specific (and critical performance code) is written in C / C ++.

-2
source

All Articles