[python-win32] CastTo interface from other library
Pieter Aarnoutse
paarnoutse at gmail.com
Mon Jan 20 21:46:18 CET 2014
In the win32com.client class CastTo method, it is assumed that the
target interface type exists in the same library as the object to be
casted. To work around that issue, I modified the method with an
optional argument stating the target interface's library, as follows:
def CastTo_mod(ob, target, typelib = None):
"""'Cast' a COM object to another interface"""
mod = None
if not typelib is None: # caller provided typelib of target
mod = gencache.MakeModuleForTypelib(typelib.clsid, typelib.lcid,
int(typelib.major), int(typelib.minor))
if not hasattr(mod, target):
raise ValueError("The interface name '%s' does not appear in the " \
"assigned library %r" % (target, typelib.ver_desc))
# todo - should support target being an IID
elif hasattr(target, "index"): # string like
# for now, we assume makepy for this to work.
# ... <snip> ....
mod = gencache.GetModuleForCLSID(target_clsid)
if not mod is None:
target_class = getattr(mod, target)
# resolve coclass to interface
target_class = getattr(target_class, "default_interface", target_class)
return target_class(ob) # auto QI magic happens
raise ValueError
after which I can cast to the type from some other library (targetlib) like
object = CastTo(object, 'targetinterfacename', targetlib)
where targetlib is a TypelibSpec taken from a search by name in the
list returned from selecttlb.EnumTlbs().
Any chance we can have some functionality like that in the release?
Thanks, Pieter
More information about the python-win32
mailing list