views:

316

answers:

3

Im writing a BHO for internet explorer where i need to call javascript methods on all open browser instances from a 'static' (or a 'global') callback method. I'm running into issues that i'm sure are related to multi-threading in COM. I had few general questions regarding this (i am new to windows programming!).

  1. Every browser would have its own IWebBrowser2 object pointed to by CComPtr. If i have a static callback method in my BHO class, which thread would that callback arrive on? Would it be anyone of the BHO threads that were created by IE?

  2. I tried to caching all the IWebBrowser2 pointers created in every BHO and access them later from the static method. However, i think there are some issues of un/marshalling involved. Firstly, would this work? Also, any suggestions on a good/(or different) approach on doing this?

~Thanks

A: 

The answer to 1 depends on the threading model that you specify for your BHO. If you specify ThreadingModel as Apartment, COM will marshal all calls to your object (within each iexplore.exe process) to the same thread. If you specify ThreadingModel as Free or Both, your object may be accessed on any thread.

The answer to 2 is yes, it would work. It is generally safe to call COM methods from any thread you like, because each object advertises its threading model when it is registered and COM itself is then responsible for handling any marshalling that must occur as a result.

You might find the following links to articles about COM threading models interesting:

Phil Booth
A: 

I tried using the Free threading model in my BHO which allows access to any object from any thread. I saved the CComPtr m_spWebBrowser; as a global variable (for now i'm not storing an array of pointers, just the pointer to the last created IE instance). Then in my static method i access m_spWebBrowser and try to call a javascript method on the IE instance. This line doesn't return S_OK {hr = spHTMLDoc->get_parentWindow(&HTML2Wind);}, the same line crashes the browser if i use the Apartment threading model. Any suggestions on what must be going wrong?

n_plus
From what you say it sounds like the second half of my answer is probably wrong in that case; sorry. You may want to try asking this part as a new question, or editing the question above so that this part is more visible. Less people are likely to see it down here, I suspect. I'm not sure what the problem is myself, unfortunately.
Phil Booth
A: 

Use the GlobalInterfaceTable to access objects across threads.

n_plus