## Goals
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
tar xvf Python-2.7.13.tgz cd Python-2.7.13 mkdir build cd build ../configure --prefix=/home/me/pythonPKG --enable-unicode=ucs4 --disable-ipv6 --enable-shared make -j20 make 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.
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++.
#include<python2.7/Python.h> intmain(){ Py_SetProgramName("myPythonProgram"); Py_Initialize(); // parDict is a parameter to send to python function PyObject * parDict; parDict = PyDict_New(); PyDict_SetItemString(parDict, "x0", PyFloat_FromDouble(1.0)); // run python code to load functions PyRun_SimpleString("exec(open('cpptest.py').read())"); // get function showval from __main__ PyObject* main_module = PyImport_AddModule("__main__"); PyObject* global_dict = PyModule_GetDict(main_module); PyObject* func = PyDict_GetItemString(global_dict, "showval"); // parameter should be a tuple PyObject* par = PyTuple_Pack(1, parDict); // call the function PyObject_CallObject(func, par); Py_Finalize(); }
Function defined in cpptest.py is:
1 2 3 4 5
import numpy as np defshowval(par): print"in function showval" print par print np.array([1, 2, 3])
we get the result:
1 2 3
in function showval {'x0': 1.0} [1 2 3]
Conclusion
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.