[python-win32] Convert PyIDispatch object to struct IDispatch*
Thomas Heller
theller at ctypes.org
Fri Apr 11 18:31:03 CEST 2008
Huayang Xia schrieb:
> I am trying to use ctypes to call dll functions. One of the functions
> requires argument "struct IDispatch* ". I do have a PyIDispatch object
> in python. How can I convert this "PyIDispatch object" to "struct
> IDispatch* "?
> Thanks in advance.
The only way (that I know of) to retrieve the 'IDispatch*' pointer
from the PyIDispatch object is to print it:
>>> from win32com.client import Dispatch
>>> ie = Dispatch("InternetExplorer.Application")
>>> print ie
Windows Internet Explorer
>>> repr(ie)
'<COMObject InternetExplorer.Application>'
>>> print ie._oleobj_
<PyIDispatch at 0xb17fb4 with obj at 0x27005c>
>>>
The last number is the pointer in question, you can parse it from the repr
and pass it to the ctypes function call.
For fun, attached is a script that creates a comtypes IDispatch pointer
from the PyIDispatch object.
Thomas
<snip>
# Shows how to convert an pywin32 PyIDispatch object
# into a comtypes COM pointer.
from win32com.client import Dispatch
d = Dispatch("InternetExplorer.Application")
x = d._oleobj_
print repr(x)
# repr(x) is like this:
# <PyIDispatch at 0xb12fac with obj at 0x2700b4>
#
# The last number is the address of the IDispatch pointer:
addr = int(repr(x).split()[-1][2:-1], 16)
print hex(addr)
from ctypes import *
from comtypes.automation import IDispatch
from _ctypes import CopyComPointer
# create a NULL comtypes pointer
p = POINTER(IDispatch)()
# put the IDispatch pointer into the comtypes IDispatch
# pointer:
cast(byref(p), POINTER(c_void_p))[0] = addr
# Call AddRef(), since the comtypes pointer will call Release() when
# it goes away:
p.AddRef()
print p
<snip/>
More information about the python-win32
mailing list