Compile Python code and link it to a C ++ program?

I am well aware of the many features that allow C code to run python code and vice versa (Cython, Boost.Python, ...). However, if I am mistaken, all of these approaches will simply “name” the corresponding python scripts and control the interactions between the C program and the python script. Therefore installation of python is required.

In my situation, I would like a standalone solution where my Python code can be somehow compiled and linked to my main C ++ program. I had hopes with Cython, as it allowed me to compile my script and create a .so file. However, I did not seem to be able to “link” this .so file to my C ++ program. I tried to do the following:

A simple python script containing a multiply (a, b) function that returns a * b; I created the libmultiply.so file using cython. A short Cpp file that displays the result of multiplication (5.2):

int multiply(int, int); int main() { std::cout << multiply(5,2) << std::endl; } 

I create: g ++ test.cpp -L / home / jerome / -lmultiply

Which gives me an error:

 test.cpp:(.text+0x2b): undefined reference to `multiply(int, int)' collect2: error: ld returned 1 exit status 

I'm not sure what I tried makes sense, but I hope this gives you an idea of ​​what I would like to achieve.

+5
source share
1 answer

Shed Skin is the closest I could find. It compiles a typed subset of Python in C ++. Probably not as reliable as we would like, but this is a strange use case. If you like to write something yourself, you can take a look at LLVM , which was used to create things similar to what you want.

Change 1:

I just found this list of python's awesome stuff on github, Awesome-python , and it references Pyston , which is an implementation of LLVM in python. It may be better suited for what you need, or a starting point for a Python bridge for C ++.

+2
source

Source: https://habr.com/ru/post/1209111/


All Articles