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.
Here, we compile python into dynamic link libraries.
Download python from python.org1wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tgz
Unzip and build the python1234567tar xvf Python-2.7.13.tgzcd Python-2.7.13mkdir buildcd build../configure --prefix=/home/me/ProgramFiles --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 support123wget https://bootstrap.pypa.io/get-pip.py --no-check-certificate/home/me/ProgramFiles/bin/python get-pip.pypip install numpy
In this charpter, we begin with a toy example to show how to run python code in C++.
The code should be compiled with
The Program will print “Hello World.” on the screen.
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:
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.