我试图在Python的一个新线程中从dll创建一个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()
这是我得到的错误跟踪:
^{pr2}$有什么想法吗?在
您需要在一个线程上调用
CoInitialize()
(或CoInitializeEx()
),然后才能在该线程上创建COM对象。在据我所知(很久以前我用COM组件编写了很多程序),如果COM对象使用STA,则必须在每个线程上调用CoInitialize
http://msdn.microsoft.com/en-us/library/ms678543(VS.85).aspx
但我不知道如何在python中调用这个函数。在
这是MSDN文档
http://msdn.microsoft.com/en-us/library/ms678543(VS.85).aspx
为了更新当前使用PyCharm和Python 2.7的体验: 您需要导入:
然后运行线程:
^{pr2}$PyCharm与STA公寓混淆,需要启用真正的多线程。在
每个
CoInitialize()
都以CoUninitialize()
结尾,这一点很重要,因此请确保您的代码也遵循此规则,以防出现错误。在相关问题 更多 >
编程相关推荐