我想在Python中的新線程創建DLL中的COM對象 - 這樣我就可以運行在該線程消息泵:爲什麼我無法在Python中的新線程中創建COM對象?
from comtypes.client import CreateObject
import threading
class MessageThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True
def run(self):
print "Thread starting"
connection = CreateObject("IDMessaging.IDMMFileConnection")
print "connection created"
a = CreateObject("IDMessaging.IDMMFileConnection")
print "aConnection created"
t = MessageThread()
t.start()
這是錯誤跟蹤我得到:
aConnection created
Thread starting
>>> Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\python26\lib\threading.py", line 532, in __bootstrap_inner
self.run()
File "fred.py", line 99, in run
self.connection = CreateObject("IDMessaging.IDMMFileConnection")
File "c:\python26\lib\site-packages\comtypes\client\__init__.py", line 235, in CreateObject
obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
File "c:\python26\lib\site-packages\comtypes\__init__.py", line 1145, in CoCreateInstance
_ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
File "_ctypes/callproc.c", line 925, in GetResult
WindowsError: [Error -2147221008] CoInitialize has not been called
任何想法?
無論對象使用什麼,都需要CoInitializeEx()。 – sharptooth 2010-07-14 13:30:28
很多thx給你們兩個...我剛剛做到了,現在我ole32.dll似乎不會從CoCreateInstance返回。我在開始消息泵之前嘗試創建對象 - 是嗎? – DangerMouse 2010-07-14 14:17:18
明白了......我的COM DLL是在VB6中實現的,我將它設置爲STA而不是單元線程......現在都在工作......在一個單獨的線程上有發送消息給Excel的COM對象;) – DangerMouse 2010-07-14 15:09:05