【问题标题】:Creating a COM object with comtypes使用 comtypes 创建 COM 对象
【发布时间】:2015-06-17 04:59:09
【问题描述】:

我正在尝试将一些旧的 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'

有什么想法吗?

【问题讨论】:

    标签: python comtypes


    【解决方案1】:

    确保为相同的平台类型编译 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
    

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2013-04-10
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2011-03-05
      • 2017-06-16
      • 2018-03-13
      • 1970-01-01
      相关资源
      最近更新 更多