COM and Threads

Roger Upole rupole at hotmail.com
Fri Oct 13 03:17:08 EDT 2006


"Teja" <tejovathi.p at gmail.com> wrote:
>
> Roger Upole wrote:
>
>> "Teja" <tejovathi.p at gmail.com> wrote:
>> >
>> > Roger Upole wrote:
>> >
>> >> "Teja" <tejovathi.p at gmail.com> wrote:
>> >> >I have an application which uses COM 's Dispatch to create a COM based
>> >> > object. Now I need to upgrade the application to a threaded one. But
>> >> > its giving an error that COM and threads wont go together. Specifically
>> >> > its an attribute error at the point where COM object is invoked. Any
>> >> > pointers please??????
>> >> >
>> >>
>> >> An actual traceback would help.
>> >> At a guess, when using COM in a thread
>> >> you need to call pythoncom.CoInitialize and
>> >> CoUninitialize yourself.
>> >>
>> >>      Roger
>> >
>> > Actually Roger, this is the scenario....
>> >
>> > I create a COM object at the beginnning of the main thread. In the sub
>> > thread, I need to access the same instance of the COM object. If it
>> > were a normal object ie. not a COM obj, i was able to do it. But if it
>> > were a COM object, its giving an attribute error? Should I pass a COM
>> > object to the thread. If so How? Please let me know ASAP... Thnks
>> >
>>
>> To pass COM objects between threads, usually they'll need to be marshaled
>> using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled
>> with pythoncom.CoGetInterfaceAndReleaseStream.
>>
>>          Roger
>
> I really appreciate your quick reply....Can u please let me know how to
> do marshalling and unmarshalling or any good refrences to do it.
> Because i tried to do it. I got some errors ans so I left it...
>
> Thnks again...
>

Here's a simple example using Internet Explorer.

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

def nav(istream, dest):
    pythoncom.CoInitialize()
    d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch)
    my_ie=win32com.client.Dispatch(d)
    my_ie.Navigate(dest)
    pythoncom.CoUninitialize()

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
thread.start_new_thread(nav, (s, 'www.google.com'))

      Roger





More information about the Python-list mailing list