Problem embedding in small Win32 App

Brad Johnson Brad.Johnson at
Fri Jul 27 21:06:32 CEST 2007

I received no responses yesterday, this is a repost. I'm still stuck on
this one ladies and gentlemen, and I'm sure it's one of those simple
things (isn't it always?)

I am creating a small test application in Windows to test the embedding
of the interpreter in order to execute arbitrary Python statements and
print their results, all via a dialog application.

Strings are sent to the interpreter via:

	PyRun_String(CString(*pbstrInput), Py_file_input, _d, _d);

Where _d is my global dictionary.

I would like to capture the output, so I created a small class to extend

      PyRun_String("class OutputCatcher:\n"
        "\tdef __init__(self):\n"
        "\tdef write(self, stuff):\n"
        "\t\ = stuff\n\n"
        "import sys\n"
        "_outcatcher = OutputCatcher()\n"
        "sys.stdout = _outcatcher\n",
        Py_file_input, _d, _d);

Using this class, I thought I could access "" to get the
last thing written to sys.stdout, and this does seem to work using the
following code:

      PyObject* o = PyDict_GetItemString(_d, "_outcatcher");
      PyObject* a = PyObject_GetAttrString(o, "data");
      ::MessageBox(NULL, PyString_AsString(a), _T(""), NULL);

However, it only works twice. On the third try, I get an access
violation trying to access the stdout object (for a print statement).
The pointer appears to be valid, but all of the data has overwritten
with 0xDBDBDBDB, with obvious consequences. 

Thanks for your help in advance.

~Brad Johnson

More information about the Python-list mailing list