27.7.1.4. Embedding Python in another application
Here we will add some better examples and explanations for: https://docs.python.org/3/extending/embedding.html#very-high-level-embedding
"Embedding Python" basically means calling the Python interpreter from C, and possibly passing values between the two.
These examples show to to embed the Python interpreter into a C/C++ application to interface between them
-
userland/libs/python_embed/eval.c: this example simply does
evala Python string in C, and don’t communicate any values between the two.It could be used to call external commands that have external side effects, but it is not very exciting.
-
userland/libs/python_embed/pure.c: this example actually defines some Python classes and functions from C, implementing those entirely in C.
The C program that defines those classes then instantiates the interpreter calls some regular Python code from it: userland/libs/python_embed/pure.py
The regular Python code can then use the native C classes as if they were defined in Python.
Finally, the Python returns values back to the C code that called the interpreter.
-
userland/libs/python_embed/pure_cpp.cpp: C version of the above, the main goal of this example is to show how to interface with C classes.
One notable user of Python embedding is the gem5 simulator, see also: gem5 vs QEMU. gem5 embeds the Python interpreter in order to interpret scripts as seen from the CLI:
build/ARM/gem5.opt configs/example/fs.py
gem5 then runs that Python script, which instantiates C classes defined from Python, and then finally hands back control to the C runtime to run the actual simulation faster.