#include <stdio.h>
#include <Python.h>
#include <string.h>

PyObject* getObject(const char* string_name)
{
  PyObject *evalModule;
  PyObject *evalDict;
  PyObject *evalVal;
  evalModule = PyImport_AddModule( (char*)"__main__" );
  evalDict = PyModule_GetDict( evalModule );
  evalVal = PyDict_GetItemString( evalDict, string_name);
  return evalVal;
}

PyObject* getObjectInModule(const char* objectName, const char* moduleName)
{
  PyObject *evalModule;
  PyObject *evalDict;
  PyObject *evalVal;
  evalModule = PyImport_AddModule( moduleName );
  evalDict = PyModule_GetDict( evalModule );
  evalVal = PyDict_GetItemString( evalDict, objectName );
  return evalVal;
}

void execInModule(const char* payload, const char* moduleName) {
    PyObject *evalModule;
    PyObject *evalDict;
    PyObject *evalVal;
    evalModule = PyImport_AddModule(moduleName);
    PyObject *globals = PyModule_GetDict(evalModule);
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
    PyObject *locals = Py_BuildValue("{}");
    PyObject *result = PyRun_StringFlags(payload,
                                         Py_file_input,
                                         globals,
                                         globals,
                                         NULL);
    
    if ( PyErr_Occurred() ) {PyErr_Print();PyErr_Clear();}
    return;
}

void print_object(PyObject* object)
{
  PyObject_Print(object, stdout, 0);
}

void finalizer(PyObject* p) {
    Py_DecRef(p);
}

typedef void funcType(PyObject*);
typedef funcType * pFuncType;

pFuncType gimmeFunc(int dummy) {
    return &finalizer;
}


/*int main() {*/
    /*Py_Initialize();*/
    /*[> PyRun_SimpleString("x = 3"); <]*/
    /*execInModule("def x(y):\n    print(y)\n    import traceback\n    return 0", "foo");*/
    /*PyObject *x = getObjectInModule("x", "foo");*/
    /*PyObject *result = PyObject_CallObject(x, Py_BuildValue("(i)", 5));*/
    /*print_object(result);*/
    /*printf("\n");*/
/*}*/
