def __comtype_to_pywin_obj(ptr, interface): """Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object. 'interface' specifies the interface we want; it must be a comtypes interface class. The interface must be implemented by the object; and the interface must be known to pythoncom. """ com_obj = PyDLL(pythoncom.__file__).PyCom_PyObjectFromIUnknown com_obj.restype = ctypes.py_object com_obj.argtypes = (ctypes.POINTER(IUnknown), ctypes.c_void_p, BOOL) # noinspection PyProtectedMember return com_obj(ptr._comobj, byref(interface._iid_), True)
# Fortunately this function is exported by the dll... # # This is the C prototype; we must pass 'True' as third argument: # # PyObject *PyCom_PyObjectFromIUnknown(IUnknown *punk, REFIID riid, BOOL bAddRef) _PyCom_PyObjectFromIUnknown = PyDLL( pythoncom.__file__).PyCom_PyObjectFromIUnknown _PyCom_PyObjectFromIUnknown.restype = py_object _PyCom_PyObjectFromIUnknown.argtypes = (POINTER(IUnknown), c_void_p, BOOL) def comtypes2pywin(ptr, interface=None): """Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object. 'interface' specifies the interface we want; it must be a comtypes interface class. The interface must be implemented by the object; and the interface must be known to pythoncom.
requires("pythoncom") import pythoncom import win32com.client # We use the PyCom_PyObjectFromIUnknown function in pythoncom25.dll to # convert a comtypes COM pointer into a pythoncom COM pointer. # Fortunately this function is exported by the dll... # # This is the C prototype; we must pass 'True' as third argument: # # PyObject *PyCom_PyObjectFromIUnknown(IUnknown *punk, REFIID riid, BOOL bAddRef) _PyCom_PyObjectFromIUnknown = PyDLL(pythoncom.__file__).PyCom_PyObjectFromIUnknown _PyCom_PyObjectFromIUnknown.restype = py_object _PyCom_PyObjectFromIUnknown.argtypes = (POINTER(IUnknown), c_void_p, BOOL) def comtypes2pywin(ptr, interface=None): """Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object. 'interface' specifies the interface we want; it must be a comtypes interface class. The interface must be implemented by the object; and the interface must be known to pythoncom. If 'interface' is specified, comtypes.IUnknown is used. """ if interface is None: interface = IUnknown return _PyCom_PyObjectFromIUnknown(ptr, byref(interface._iid_), True)