Skip to content

Instantly share code, notes, and snippets.

@EBNull
Created November 19, 2012 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EBNull/4114287 to your computer and use it in GitHub Desktop.
Save EBNull/4114287 to your computer and use it in GitHub Desktop.
Create an instance of a COM object with IClassFactory2 for objects that require licensing.
import pythoncom
import win32com.client
from uuid import UUID
from ctypes import OleDLL, WinDLL, c_long, c_ulong, byref, WINFUNCTYPE, POINTER, c_char_p, pointer
from ctypes.wintypes import HRESULT
IID_IClassFactory2 = "{B196B28F-BAB4-101A-B69C-00AA00341D07}"
def CoCreateInstanceLicenced(clsid_class, iid_interface=pythoncom.IID_IDispatch, key='', dwClsContext=pythoncom.CLSCTX_SERVER, pythoncom_iid_interface=pythoncom.IID_IDispatch, pythoncom_wrapdisp=True):
"""Uses IClassFactory2::CreateInstanceLic to create a COM object given a licence key."""
ole = OleDLL("Ole32.dll")
ole_aut = WinDLL("OleAut32.dll")
clsid_class = UUID(clsid_class).bytes_le
iclassfactory2 = UUID(IID_IClassFactory2).bytes_le
com_classfactory = c_ulong(0)
hr_gco = ole.CoGetClassObject(clsid_class, dwClsContext, None, iclassfactory2, byref(com_classfactory))
obj_ptr = c_ulong(0)
proto_icf2_base = WINFUNCTYPE(HRESULT,
c_ulong,
c_ulong,
c_char_p,
c_ulong,
POINTER(c_ulong),
)
IClassFactory2__CreateInstanceLic = proto_icf2_base(7, 'CreateInstanceLic', (
(1 | 4, 'pUnkOuter'),
(1 | 4, 'pUnkReserved'),
(1, 'riid'),
(1, 'bstrKey'),
(2, 'ppvObj'),
), iclassfactory2)
req_if = UUID(iid_interface).bytes_le
key_bstr = ole_aut.SysAllocString(unicode(key))
try:
obj = IClassFactory2__CreateInstanceLic(com_classfactory, c_char_p(req_if), key_bstr)
disp_obj = pythoncom.ObjectFromAddress(obj, pythoncom_iid_interface)
if pythoncom_wrapdisp:
return win32com.client.__WrapDispatch(disp_obj)
return disp_obj
finally:
if key_bstr:
ole_aut.SysFreeString(key_bstr)
if com_classfactory:
IUnknown__Release = WINFUNCTYPE(HRESULT)(2, 'Release', (), pythoncom.IID_IUnknown)
IUnknown__Release(com_classfactory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment