[Python.NET] CLR + wxPython + OLE initialization

Brian Lloyd brian at zope.com
Sat Apr 10 23:31:59 EDT 2004


> Today I found that in my wxPython apps, adding a CLR
> import at the top of the files causes wxPython's
> mainloop to generate a warning message box which reads
> "Could not initialize OLE".  Otherwise, the
> application seemed functional.  I experimented with
> it, and it seems that delaying CLR-related imports
> until after the wx Mainloop has started does the
> trick.
> 
> <snip>

It's late, so forgive any errors in the details, but...

This has to do with Deep Voodoo (tm) regarding the CLR and 
COM compartment initialization.

Essentially, whenever you use interop (marshalling to/from 
native code, etc.), the CLR will have made sure that the 
process has been initialized to some COM apartment state.

Because Python for .NET uses interop extensively (to join the 
managed world with unmanaged CPython), by the time 'import CLR' 
finishes, you will be in whatever kind of apartment the CLR deems 
the default.

By your report (and my hazy memory), if you import CLR first you 
are probably getting the thread initialized as MTA, and OleInitialize 
probably wants the thread to either be uninitialized or initialized 
to STA.

Your workaround is probably as good as any - there is no real 
way to change the apartment state from Python once its been 
intialized (without creating a new thread and doing a lot of 
things by hand, etc.), since either the CLR itself or some 
specific unmanaged call (like your OleInitialize) will have 
made the choice already by the time the CLR/Python layer is 
bootstrapped.

Hope this helps!



Brian Lloyd        brian at zope.com
V.P. Engineering   540.361.1716              
Zope Corporation   http://www.zope.com 





More information about the PythonDotNet mailing list