Wednesday, November 6, 2013

How to Embed Python into C++

Below is a simple example how to embed Python into C++.
#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

No comments:

Post a Comment