How to access COM objects from different apartment models?

三世轮回 提交于 2019-12-23 17:04:10

问题


I have a multi-threaded C++Builder GUI app, which communicates with a third-party app via COM.

I need to call methods of the COM object from several threads, and I'm protecting access with a mutex. Apparently, the main GUI thread must use STA model, but my worker threads need to use MTA. The COM object is constructed in an MTA thread.

Everything works fine except access to the COM object from the GUI thread, due to the MTA/STA mismatch.

I've read a bit about marshalling, but haven't tried to implement it, because the examples I've seen seem to require different access semantics depending the the current apartment model, and I really would like to have code that (from a programmer's POV) doesn't care about the current apartment model.

So, is there an idiomatic way to write COM code that operates on the 'same' object, but can be called from both STA and MTA threads?


回答1:


Put the COM object interface into the Global Interface Table and let the GIT handle the marshalling for you. When any thread requests the COM interface, the GIT checks the calling apartment and will provide a direct pointer or a suitable proxy accordingly. Your code won't know the difference (or care), just use the returned interface normally as needed.

This is documented on MSDN:

Accessing Interfaces Across Apartments



来源:https://stackoverflow.com/questions/7715610/how-to-access-com-objects-from-different-apartment-models

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!