Problem Embedding Python in small Win32 App

Brad Johnson Brad.Johnson at ballardtech.com
Thu Jul 26 19:31:52 CEST 2007


I am just entering the world of Python embedding and I am running into a
bug I am having a hard time fixing. Please be gentle.

 

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
Python

 

      PyRun_String("class OutputCatcher:\n"

        "\tdef __init__(self):\n"

        "\t\tself.data=''\n"

        "\tdef write(self, stuff):\n"

        "\t\tself.data = 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 "_outcatcher.data" 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 any help.

 

~Brad Johnson

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070726/eb6820eb/attachment.html>


More information about the Python-list mailing list