[python-win32] Accessing Interfaces

Tim Roberts timr at probo.com
Fri Feb 20 23:56:38 CET 2009


Te-jé Rodgers wrote:
> Could you point me to an example of how to use COM interfaces with pywin32? I've skimmed the documentation but it seems to be geared at someone who already knows what he's doing.
>   

It's not really all that complicated, in general, because PyWin32
automatically generates "wrapper" classes to hide the ugly details.

Here's a quick example of how to use COM to open up Word, make it
visible, and enter a few characters of text.  You can even type this at
the interactive prompt to watch the progress:

    import win32com.client
    word = win32com.client.Dispatch( "Word.Application" )
    word.Visible = 1
    word.Selection.TypeText( Text="abc" )

"word" in that code is a COM object.  As you can see, once you HAVE the
object, you just treat it like a Python object.  Pythoncom takes care of
the mapping.

However, in the case of DirectWrite, things are a little more
complicated, because you can't use the normal win32com Dispatch
mechanism to create the object.  You have to use DWriteCreateFactory. 
And because it's only in Windows 7, DWriteCreateFactory is not in any of
the pywin32 wrappers yet.  So, if you really need to do this with
Python, you will end up using ctypes to call DWriteCreateFactory, and
ctypes/comtypes to call the member functions.

Are you sure you want to do this?  ;)  Until someone writes a wrapper
layer, it would probably be more productive for you to use C++.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list