Embedding Python in C++

Adding python scripting capabilities to your code is an interesting thing to do, it can help you enhance an application without as much hard work. This is just an example on how to use code from memory as part of your program.


// Embedded Py.cpp
//

#include "stdafx.h"
#include
#undef _DEBUG /* Link with python24.lib and not python24_d.lib */
#include

using namespace std;

/* Python function code */
char script[] =
"def doSomeStuff():\n"
" import sys\n"
" print sys\n"
" return 3+2+2";

int _tmain(int argc, _TCHAR* argv[])
{
PyObject *pName = NULL, *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pCode = NULL, *pReturn = NULL;
Py_Initialize();

/* Compile the script defined in the array script */
pCode = Py_CompileString(script, "mini-script", Py_file_input);

if (!pCode || PyErr_Occurred())
{
PyErr_Print();
return 0;
}

/* Import the code compiled */
pModule = PyImport_ExecCodeModule("mini-script", pCode);

if (!pModule || PyErr_Occurred())
{
PyErr_Print();
return 0;
}

/* Get the Dictionary of the module */
pDict = PyModule_GetDict(pModule);

if (!pDict || PyErr_Occurred())
{
PyErr_Print();
return 0;
}

/* Grab the function with the name doSomeStuff() */
pFunc = PyDict_GetItemString(pDict, "doSomeStuff");

if (!pFunc || PyErr_Occurred())
{
PyErr_Print();
return 0;
}

/* Call the function */
pReturn = PyObject_CallObject(pFunc, NULL);

if (!pReturn || PyErr_Occurred())
{
PyErr_Print();
return 0;
}

/* Make sure return value is of int type */
if (PyInt_Check(pReturn))
{
long returnOfFunc = PyInt_AsLong(pReturn);
cout << "The return of doSomeStuff() function is: " << returnOfFunc << endl;
}

/* Cleanup */
Py_XDECREF(pReturn);
Py_XDECREF(pCode);
Py_XDECREF(pFunc);
Py_XDECREF(pDict);
Py_XDECREF(pModule);
Py_Finalize();

return 0;
}

Tags: