[python-win32] how to get the interface of an COM object?

Thomas Heller theller at ctypes.org
Tue Nov 14 13:19:05 CET 2006


Bruce Who schrieb:
> Hi, Thomas
> 
> Finally I make it to create a COM object:
> 
> class EventSink:
>     def OnLoadFinished(self):
>         print 'load finished'
> 
> o = comtypes.client.CreateObject("SomeObj2.SomeObj.1", sink=EventSink())
> 
> but the EventSink.OnLoadFinished() is never called, and I still donnot
> know how to get an interface, :-(


Well, comtypes.client.CreateObject /returns/ a pointer to a COM interface.
If it is not the interface you want, you can call o.QueryInterface(IOtherInterface)
on it - how you get or create the IOtherInterface Python class that 'describes'
the interface is another question.  If the COM object supplies type information
then comtypes generates a Python wrapper for the type library automatically
in the 'comtypes.gen' package.  The module name is derived from the type library,
for example for InternetExplorer  the typelib is name comtypes.gen.SHDocVw (Note
that this is a very shallow module, it imports everything from another module that
is named after the GUID and version from the typelib; for IE it is
'comtypes.gen._EAB22AC0_30C1_11CF_A7EB_0000C05BAE0B_0_1_1').
You can import the interfaces from any of these modules.

For the events: First, the event handler methods receive an additional argument
'this' just after the 'self', this is an implementation detail of comtypes; which
mirrors that COM methods you *implement* also receive this argument.
Then, it could be that the name of the method is wrong; comtypes does *not* prepend
an 'On' to the method name.

A useful event sink for COM objects is one that responds to __getattr__ by dynamically
creating event handlers, the attached script demonstrates this (for IE, again).

Oh, there 'may* be a totally different reason why you don't receive events:
By default, comtypes (like pythoncom) creates a single-threaded COM appartment,
in which you usually should run a message pump.

Thomas

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: test_events.py
Url: http://mail.python.org/pipermail/python-win32/attachments/20061114/9e0490d3/attachment.pot 


More information about the Python-win32 mailing list