comtypes

Introduction

Pros and Cons

Pros

  • pure python implementation
  • direct use kernel32.dll, ole32.dll, oleaut32.dll, etc. no wrapping extension modules like pywin32 pythoncom.dll
  • can use custom COM interface not based on IDispatch interface

Cons

  • No ready-made data structures and constants for win32 sdk api. You have to implement.

Using Type Library for Early Bounding

comtypes.client.GetModule

  • parse type library and create python module
    • location: C:\Python26\Lib\site-packages\comtypes-0.6.2-py2.6.egg\comtypes\gen
    • creates two .py files: one for typelib name and the other for typelib id
      • for example, Excel.py and _00020813_0000_0000_C000_000000000046_0_1_6.py
  • usage
    • input com module name or (TypeLib Id, Major Version, Minor Version) tuple
>> tlb = comtypes.client.GetModule(("{00020813-0000-0000-C000-000000000046}", 1, 6))

or
>> tlb = comtypes.client.GetModule("C:\Program Files\Microsoft Office\Office12\EXCEL.EXE")
  • module contents
    • IDispatch-based interface class
    • CoClass class
    • enumeration constants
  • automatically executed by CreateObject command

Getting COM interface and object

  • use 3 method
    • comtypes.client.CreateObject (most case)
    • comtypes.client.CoGetObject
    • comtypes.client.GetActiveObject

comtypes.client.CreateObject

  • ole32.CoCreateInstance, ole32.CoCreateInstanceEx 의 wrapper

comtypes.client.CoGetObject

  • ole32.CoGetObject 의 wrapper
  • use COM display name

comtypes.client.GetActiveObject

  • oleaut32.GetActiveObject 의 wrapper
  • get COM object already running

Event Processing

EventSink Class

  • method name : EventIntefaceName_EventName
    • example: AppEvent_NewWorkbook

ActiveX Control Hosting

COM Server