Wednesday, November 6, 2013

How to Embed Python into C++

Below is a simple example how to embed Python into C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <Python.h>
 
int main(int argc, char* argv[]) {
    Py_Initialize();
    PyRun_SimpleString("import math; a = 100; result = math.log10(100)");
    PyObject* module = PyImport_AddModule("__main__");
    PyObject* dictionary = PyModule_GetDict(module);
    PyObject* result = PyDict_GetItemString(dictionary, "result");
    double resultValue = PyFloat_AsDouble(result);
    std::cout << "result: " << resultValue << std::endl;
    Py_Finalize();
    return 0;
}
Output:
result: 2