Embedding Python into an MFC app - thread problems.

John DeFord john.deford at staarinc.com
Tue Aug 24 17:16:44 EDT 1999


I've embedded Python + win32 extensions into my MFC app with the following
code scrap in my app's InitInstance member (taken from Pythonwin embedding
documentation):

 Py_Initialize();

 glue.bShouldAbandonThreadState = false;  // Wasn't in example!

 if (!glue.DynamicApplicationInit("import initscore", NULL))

 // Assuming you have a ReportError method - do whatever makes sense!
  AfxMessageBox("Could not attach to the Python win32ui extensions.",
MB_OK);
  return FALSE;
 }

ptPythonThread = PyThreadState_Swap(NULL); // Wasn't in example!

I'm using MSVC++ 6.0, and my application is responsible for displaying all
windows at the moment.  The two lines commented by "// Wasn't in example",
plus the following lines bracketing subsequent Python calls seemed to be
required to get it to work:

  PyThreadState* ptThread = ((CCtest2App*)AfxGetApp())->ptPythonThread; //
Stored by call in InitInstance.
  PyThreadState* _save = PyThreadState_Swap(ptThread);

....// various Python C api function calls...

  PyThreadState_Swap(NULL);

Without all this thread swapping Python throws a fatal error saying current
thread is NULL.  Am I missing something, or is this additional code really
necessary?  The sources I'm working with are all the August 1999 versions.

John







More information about the Python-list mailing list