[python-win32] "Casting" COM objects

Jens B. Jorgensen jens.jorgensen@tallan.com
Thu, 03 Apr 2003 09:32:49 -0600

Paul Prescod wrote:

> Jens B. Jorgensen wrote:
>> Based on the fact that makepy does its work by looking through type 
>> libraries it would be possible for it to generate the type traversal 
>> mechanisms you speak of, but unfortunately (or fortunately?) it 
>> doesn't as far as I know.
> I was thinking more of a feature I could call explicitly at runtime 
> than something baked into the interfaces, rather than a new feature 
> for makepy. 

That's where we'd get into trouble though since for any given COM object 
there isn't a way to know what class it came from. You can try to get 
the IPersist interface to find out the CLSID but getting the CLSID 
doesn't tell you anything about what other interfaces. If you want to 
"downcast" the pointer or get another interface supported by the object 
you have to have prior knowledge. Even then this kind of downcasting 
cannot be done as downcasting anyway, you have to QueryInterface for it. 
This prior knowledge has to come from a type library. There is no 
mechanism to take an interface pointer and get the type library that 
describes the class that interface came from. Since the only way to do 
this is from a type library that's why I suggested it could be added to 

>> ... casting" the type by passing the python object reference you have 
>> to the constructor of the object wrapping the interface you want is 
>> the method that I use.
> The problem is it can be inconvienent or impossible to figure out what 
> constructor is appropriate. I'm thinking of something more dynamic 
> where I don't tell it what to do, I just tell it: "figure out what 
> class you are." 

It is inconvenient, I know. It is no wonder more recent models such as 
Java and CLR support a "reflection" interface to discover type 
information about an object pointer eh?

Jens B. Jorgensen

"With a focused commitment to our clients and our people, we deliver value through customized technology solutions"