使用comtypes创建COM对象

时间:2015-04-10 18:50:21

标签: python comtypes

我正在尝试将一些旧的VBA代码移植到Python。

在VBA中,我添加Geo3D.dll作为项目参考,然后我使用它:

Set P1 = New GEO3DLib.Point
P1.Set 1, 2, 3, 0.001

在Python中我尝试了这个:

import comtypes
import comtypes.client as cc
cc.GetModule('C:\\Program Files (x86)\\think3\\2009.3\\thinkdesign\\bin\\Geo3d.dll')
import comtypes.gen.GEO3DLib as Geo3d
pt = cc.CreateObject('Geo3d.Point', None, None, Geo3d.Point)

但是我收到了这个错误:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    pt = cc.CreateObject('Geo3d.Point', None, None, Geo3d.Point)
  File "C:\Anaconda3\lib\site-packages\comtypes\client\__init__.py", line 238, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "C:\Anaconda3\lib\site-packages\comtypes\__init__.py", line 1217, in CoCreateInstance
    iid = interface._iid_
AttributeError: type object 'Point' has no attribute '_iid_'

用最后一行替换:

pt = Geo3d.Point
pt.Set(1., 2., 3., 0.001)

我收到此错误:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    pt.Set(1., 2., 3., 0.001)
AttributeError: type object 'Point' has no attribute 'Set'

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

确保python实现和thinkdesign库针对相同的平台类型进行编译:64位或32位。

我测试了如下:

>>> p=Dispatch('Geo3d.Point')
>>> p
<win32com.gen_py.think3 thinkdesign Type Library.IPoint instance at 0x59554312>
>>> p.Set(0,0,0)
>>> p.X
0.0

或使用comtypes:

>>> point=comtypes.CoCreateInstance(comtypes.GUID.from_progid('Geo3d.Point'))
>>> ipoint=point.QueryInterface(Geo3d.IPoint)
>>> ipoint.Set(0,0,0)
0
>>> ipoint.X
0.0