proteus  1.8.1
C/C++/Fortran libraries
PyEmbeddedFunctions.h
Go to the documentation of this file.
1 #ifndef PYEMBEDDEDFUNCTIONS_H
2 #define PYEMBEDDEDFUNCTIONS_H
3 
4 #include "Python.h"
5 
6 //This function accepts a string which gets passed to the logEvent Python function in Profiling
7 static int logEvent(char* logString,int logLevel)
8 
9 //logString is the desired string: usually set with sprintf() to combine characters with numbers
10 //logLevel means the same as with the python function
11 {
12  if(!Py_IsInitialized())
13  Py_Initialize();
14  PyObject *pName=NULL, *pModule=NULL, *pFunc=NULL;
15  PyObject *pArgs=NULL, *pValue=NULL;
16 
17  pName = PyUnicode_FromString("proteus.Profiling");
18  pModule = PyImport_Import(pName);
19  Py_DECREF(pName);
20  if (pModule != NULL)
21  {
22  pFunc = PyObject_GetAttrString(pModule,"logEvent");
23  pArgs = PyTuple_New(2);
24 
25 /*
26  //This is how the embedding is done in the official Python example...but this leads to a memory leak for some reason
27  pValue = PyUnicode_FromString(logString);
28  // pValue reference stolen here:
29  PyTuple_SetItem(pArgs, 0, pValue);
30 
31  pValue = PyLong_FromLong(logLevel);
32  // pValue reference stolen here:
33  PyTuple_SetItem(pArgs, 1, pValue);
34 */
35  PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(logString));
36  PyTuple_SetItem(pArgs, 1, PyLong_FromLong(logLevel));
37 
38  PyObject_CallObject(pFunc,pArgs);
39  Py_DECREF(pFunc);
40  Py_DECREF(pArgs);
41  if(pValue !=NULL)
42  {
43  Py_DECREF(pValue);
44  Py_XDECREF(pValue);
45  }
46  }
47  else
48  {
49  PyErr_Print();
50  fprintf(stderr,"Failed to load \"%s\"\n", "proteus.Profiling");
51  return 1;
52  }
53  Py_DECREF(pModule);
54  return 0;
55 }
56 
57 #endif