[Zope-dev] COM initialization

Toby Dickenson tdickenson@oriongroup.co.uk
Tue, 27 Jul 1999 15:03:47


I've been using the code below to initialize COM correctly in a
threaded
ZServer. Without something like this, COM objects are unlikely to be
thread safe, and COM itself may deadlock. It should also avoid any
CO_E_NOTINITIALIZED errors when creating COM object.

Has anyone else noticed this kind of problem before?

Relative to alpha 4, add "import zcom; zcom.init()" in the midde of z2
 py,
"import zcom; zcom.start_of_another_zope_thread()" as the first line
of
__init__ in ZServerPublisher.py, and the module zcom.py as below.

I hope this helps,

Toby Dickenson




""" COM support for Zope.

This module initializes COM. Nothing more.

Author: Toby Dickenson

"""

# We have to use MTA threads since it is possible that a variable
# referring to a COM object might be used by multiple threads. After
# this, COM will take care of all concurrency issues automatically.

import sys

COINIT_MULTITHREADED = 0

def init():
"""Call this in the main application thread. It determines whether
COM support is available, and imports the pythoncom module for the
first time. The first import of pythoncom triggers some 'convenient'
magic, so we get that over with too."""

# Set the value in sys module that is used by pythoncom
# when first imported
sys.coinit_flags=COINIT_MULTITHREADED
try:
import pythoncom
except ImportError:
pass
else:
assert COINIT_MULTITHREADED==pythoncom.COINIT_MULTITHREADED
# This thread is now registered with COM as an MTA


def start_of_another_zope_thread():
"""Call this at the start of every thread that enters Zope."""
pythoncom=sys.modules.get('pythoncom',None)
if pythoncom:
pythoncom.CoInitializeEx(COINIT_MULTITHREADED)
# This thread is now part of the MTA