Tuesday, July 22, 2014

How to Embed Python in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <Python.h>
 
using namespace std;
 
int main() {
    Py_Initialize();
 
    string statements =
        "a = 8\n"
        "b = 2\n"
        "c = (a * b) / 2";
 
    int retVal = PyRun_SimpleString(statements.c_str());
    if (retVal == 0) {
        PyObject* m = PyImport_AddModule("__main__");
        PyObject* v = PyObject_GetAttrString(m, "c");
 
        int c = PyInt_AsLong(v);
        cout << "c: " << c << endl;
 
        Py_DECREF(v);
    }
    Py_Finalize();
    return 0;
}
Output:
c: 8