pythonportingwin32comcomtypesqueryinterface

Porting comtypes to win32com


In a Python script I have to replace usage of comtypes by win32com and pythoncom. Essentially I have this code:

from comtypes.client import CreateObject, GetEvents

object_IXXObjManager = comtypes.client.CreateObject(xxxId)
connection_IXXObjManager = GetEvents(object_IXXObjManager, IXXObjManagerEventHandler())

object_IXXObjCommunications = object_IXXObjManager.QueryInterface(comtypes.gen.XXOBJLib.IXXObjCommunications)
connection_IXXObjCommunications = GetEvents(object_IXXObjCommunications, IXXObjCommunicationEventHandler(), interface=comtypes.gen.XXOBJLib.IXXObjCommunicationsEvents)

and the target is to get similar functionality using win32com. In my understanding the event handler classes will require no changes. First part was easy:

import win32com.client
object_IXXObjManager = win32com.client.Dispatch(xxxId)
event_IXXObjManager = win32com.client.WithEvents(object_IXXObjManager, IXXObjManagerEventHandler) 

However, I got stuck when trying to map an event handler to a object from queried interface.

object_IXXObjManager._oleobj_.QueryInterface( ??? )

Could you help me? I do have general sw development experience, however limited COM knowledge.


Solution

  • The replacement for

    object_IXXObjCommunications = object_IXXObjManager.QueryInterface(comtypes.gen.XXOBJLib.IXXObjCommunications)
    

    can be like this:

    iface = object_XXObjManager._oleobj_.QueryInterface(pythoncom.IID_IDispatch)
    iface_Communications = win32com.client.CastTo(iface,"XXObjCommunications")
    connection_XXObjCommunications = win32com.client.Dispatch(iface_Communications)