We explore the method to embed python code into C++ . This is useful when we want to integrate some python code snippets into some C++ based systems. ## compile python Here, we compile python into dynamic link libraries. 1. Download python from python.org
- Unzip and build the python 1234567tar xvf Python-2.7.13.tgzcd Python-2.7.13mkdir buildcd build../configure --prefix=/home/me/pythonPKG --enable-unicode=ucs4 --disable-ipv6 --enable-sharedmake -j20make install
Here, we have almost gotten all of our necessary tools ready. However, some 3rd party library is useful when we are developing some programs such as numpy. Numpy is a powerful tool for algebra calculation in python. In order to add numpy support. We should firstly install pip and then use pip to install the numpy library.
- Add numpy support 123wget https://bootstrap.pypa.io/get-pip.py --no-check-certificate/home/me/pythonPKG/bin/python get-pip.pypip install numpy
Run Python in C++
In this charpter, we begin with a toy example to show how to run python code in C++.
Run Simple Code
The code should be compiled with
The Program will print “Hello World.” on the screen.
Run Python File
Run python file is almost the same with run some code since we just read the code file and use
exec to run it. Here we go:
code in cpptest.py:
Pass Parameters to Python Function
Passing parameters to python is a little bit difficult since we should make the parameters in C++ environment. Fortunately, Python’s C-API provide several useful apis to construct nearly all types of python data with C++.
Function defined in
we get the result:
In this post we illustrate variety of ways to invoke python code in C++ environment. Besides, the method to compile a useable python library is also presented. ## Reference  https://docs.python.org/2/c-api/index.html