How to Invoke Python Function From C++

In the process of designing the swarm robotics benchmark system, a question of how to interact with robot platforms written in Python draw a lot of my attention. I have tried to wrap the entire C++ library with Cython to provide Python APIs, may be in another post later, or to provide C++ driver code that is capable of calling the Python platform API. Simply speaking, the choice between using Python programs to call c++ functions, or using c++ programs to call Python functions. I choose the later one just to keep only one C++ as user program.

Following are the sample C++ and Python program for testing.

 

#define PY_SSIZE_T_CLEAN
#include <Python/Python.h>
#include <stdio.h>

int main() {
    printf("start cpp function\n");
    
    Py_Initialize();
    
    PyObject * sys = PyImport_ImportModule("sys");
    PyObject * path = PyObject_GetAttrString(sys, "path");
    PyList_Append(path, PyString_FromString("."));
    
    PyObject * ModuleString = PyString_FromString((char*) "py_function");
    PyObject * Module = PyImport_Import(ModuleString);
    PyObject * Dict = PyModule_GetDict(Module);
    PyObject * Func = PyDict_GetItemString(Dict, "python_test");
    PyObject * Result = PyObject_CallObject(Func, NULL);
    
    Py_Finalize();
}