Run Python Code in C++

Run Python Code in C++

By Z.H. Fu

切问录 www.fuzihao.org

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

    1
    wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tgz
  2. Unzip and build the python

    1
    2
    3
    4
    5
    6
    7
    tar xvf Python-2.7.13.tgz
    cd Python-2.7.13
    mkdir build
    cd build
    ../configure --prefix=/home/me/ProgramFiles --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.

  1. Add numpy support
    1
    2
    3
    wget https://bootstrap.pypa.io/get-pip.py --no-check-certificate
    /home/me/ProgramFiles/bin/python get-pip.py
    pip 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

1
2
3
4
5
6
7
#include <python2.7/Python.h>
int main(){
Py_SetProgramName("myPythonProgram");
Py_Initialize();
PyRun_SimpleString("print 'Hello World.'");
Py_Finalize();
}

The code should be compiled with

1
g++ pythonRun.cpp -lpython2.7 -lpthread -ldl -lutil -O2 -L/home/me/ProgramFiles/lib

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:

1
2
3
4
5
6
7
#include <python2.7/Python.h>
int main(){
Py_SetProgramName("myPythonProgram");
Py_Initialize();
PyRun_SimpleString("exec(open('cpptest.py').read())");
Py_Finalize();
}

code in cpptest.py:

1
print "hello world."

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++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <python2.7/Python.h>
int main(){
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
def showval(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.

Reference

[1] https://docs.python.org/2/c-api/index.html