Accessing unregistered COM objects from python via a registered TLB

前端 未结 3 926
悲&欢浪女
悲&欢浪女 2020-12-13 11:14

I have three pieces of code that i\'m working with at the moment:

  • A closed source application (Main.exe)
  • A closed source VB COM object implemented as
3条回答
  •  一向
    一向 (楼主)
    2020-12-13 11:47

    Here is a method I devised to load a COM object from a DLL. It was based on a lot of reading about COM, etc. I'm not 100% sure about the last lines, specifically d=. I think that only works if IID_Dispatch is passed in (which you can see if the default param).

    In addition, I believe this code leaks - for one, the DLL is never unloaded (use ctypes.windll.kernel32.FreeLibraryW) and I believe the COM ref counts for the initial class factory are off by one, and thus never get released. But still, this works for my application.

    import pythoncom
    import win32com.client
    def CreateInstanceFromDll(dll, clsid_class, iid_interface=pythoncom.IID_IDispatch, pUnkOuter=None, dwClsContext=pythoncom.CLSCTX_SERVER):
        from uuid import UUID
        from ctypes import OleDLL, c_long, byref
        e = OleDLL(dll)
        clsid_class = UUID(clsid_class).bytes_le
        iclassfactory = UUID(str(pythoncom.IID_IClassFactory)).bytes_le
        com_classfactory = c_long(0)
        hr = e.DllGetClassObject(clsid_class, iclassfactory, byref(com_classfactory))
        MyFactory = pythoncom.ObjectFromAddress(com_classfactory.value, pythoncom.IID_IClassFactory)
        i = MyFactory.CreateInstance(pUnkOuter, iid_interface)
        d = win32com.client.__WrapDispatch(i)
        return d
    

提交回复
热议问题