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

Gary Bishop gb at cs.unc.edu
Sun Mar 23 13:23:30 EST 2003


Gary Bishop <gb at cs.unc.edu> wrote:
> Thanks. I'll certainly do step 2 in my python code. 

> I assume I have to link with some library to define
> PyCom_PyObjectFromIUnknown. Do I need to build from the sources to get
> it?

> gb

For future generations of Googler's I'll answer my own question. 

First, to get access to Mark's function, I used "explicit linking" to
the dll rather than building the library from source. The code in my
SWIG interface file to link to the dll is:

----------------------
%wrapper %{
  /* get the function we need from the win32com package using explicit linking */
  typedef PyObject* (*PYCOM_PYOBJECTFROMIUNKNOWN)(IUnknown *punk, 
						  REFIID riid, 
						  BOOL bAddRef = FALSE);
  PYCOM_PYOBJECTFROMIUNKNOWN PyCom_PyObjectFromIUnknown = NULL;
  void GetPythoncomDLL() {
    /* this should use the version of figure out the name */
    HINSTANCE hDLL = LoadLibrary("pythoncom22");
    if (hDLL != NULL) {
      PyCom_PyObjectFromIUnknown = (PYCOM_PYOBJECTFROMIUNKNOWN)
	GetProcAddress(hDLL, "PyCom_PyObjectFromIUnknown");
    }
    if (hDLL == NULL || PyCom_PyObjectFromIUnknown == NULL) {
      fprintf(stderr, "Explicit link to pythoncom22.dll failed\n");
    }
  }
  %}
%init %{
  GetPythoncomDLL();
  %}
------------------

Then to convert from my COM pointer to an object accessible with
win32com I mimicked Mark's code like:

------------------
    // wrap it for use by Mark Hammond's win32com package
    PyObject* result = PyCom_PyObjectFromIUnknown(pUnk, IID_IDispatch);
------------------

Finally in the Python wrapper for the C extension, I complete the job
with:

------------------
    com = CComObject(self.ia, clsid)
    # convert it using Mark Hammdond's code
    com = WrapDispatch(com)
    if EventClass:
      com = DispatchWithEvents(com, EventClass)
    return com
------------------

I got access to those functions from Mark's module with:

------------------
import win32com.client
from win32com.client import DispatchWithEvents
WrapDispatch = win32com.client.__WrapDispatch
------------------

Thanks to Mark for the fine code!
gb





More information about the Python-list mailing list