How can I use an existing COM object pointer with win32com?

Mark Hammond mhammond at skippinet.com.au
Tue Mar 18 17:12:33 EST 2003


Gary Bishop wrote:
> In my C++ extension that wraps the Microsoft Active Accessibility API
> I can get a pointer to a IWebBrowser2 COM interface from an
> IAccessible representing the browser. I'd like to hand this pointer
> back to my Python code and use it just like I would use the object I'd
> get from
> 
> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
> 
> Can I do that? I don't want to create a new instance of Internet
> Explorer. I want to connect to a particular instance already running.
> 
> I have looked for an example of "adopting" a COM pointer but haven't
> found one.

There are 2 steps you must go through:
1) Convert the C++ interface pointer to a PyObject
2) Convert this PyObject to a "nice" win32com instance

1) is a matter of calling PyCom_PyObjectFromIUnknown(), defined in 
PythonCOM.h

2) is really a matter of calling the functions yourself from the C++ 
code using the Python API - eg, PyImport_ImportModule() to get 
win32com.client, PyObject_GetAttr() to get the function from the module, 
and PyEval_CallObject() to make the call.  (The exact names may not be 
correct there)

I am not sure how you hope to get DispatchWithEvents working, given that 
the second param is a class object - however, I am sure you have some 
plan :)  Further, I suggest that (2) actually be put in Python code. 
Your C++ code should do (1), then delegate to your own Python code. 
This code then does (2), and anything else necessary.

Mark.





More information about the Python-list mailing list