Embedding: How to set globals for PyObject_Call

Scott Gilbert xscottgjunk at yahoo.com
Mon Feb 18 12:59:53 EST 2002


Hi All.

I'm embedding Python in another library.  Basically, I'm treating
Python as a sophisticated data structures library, statement executor,
and expression evaluator.  The sample below is just to illustrate my
problem, not the actual code I'm using.

The problem is that while PyRun_String(...) allows me to pass in the
global variables dictionary, PyObject_Call(...) does not.

I dove through the code, and it appears that I need to setup a
PyFrameObject to be associated with my PyThreadState.  I wasn't able
to figure out how to do that though.

As you can see in my example below, I have the globals sitting right
there.  I just don't know how to tell Python that those are the
appropriate globals while invoking PyObject_Call(...).  A similar
problem occurs when evaluating "globals", "locals", "dir", or
functions that call those.

Is there a way around this?

Thanks in advance for any and all assistance!



#include <Python.h>

int main (int argc, char* argv) {
  PyObject* module;
  PyObject* globals;
  PyObject* vars;
  PyObject* tuple;
  PyObject* dict;
  PyObject* result;

  Py_Initialize();
  module = PyImport_AddModule("__main__");
  globals = PyModule_GetDict(module);

  vars = PyRun_String("vars", Py_eval_input, globals, globals);
  tuple = PyTuple_New(0);
  dict = PyDict_New();

  result = PyObject_Call(vars, tuple, dict);

  if (!result) {
    printf("Had a problem calling vars()\n");
    PyErr_Print();
  }

  /* skip the decrefs and finalization */

  return 0;
}



More information about the Python-list mailing list