如何从不同的公寓模型访问COM对象? [英] How to access COM objects from different apartment models?

查看:297
本文介绍了如何从不同的公寓模型访问COM对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程C ++ Builder GUI应用程序,它通过COM与第三方应用程序通信。

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

我需要调用COM的方法对象从几个线程,我保护访问与互斥。显然,主GUI线程必须使用STA模型,但我的工作线程需要使用MTA。 COM对象是在MTA线程中构造的。

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.

一切正常除了从GUI线程访问COM对象,由于MTA / STA不匹配。

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

我已经阅读了一些关于编组的信息,但没有尝试实现它,因为我看到的例子似乎需要不同的访问语义取决于当前的公寓模型,我真的想有代码(从程序员的POV)不关心当前的公寓模型。

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.

那么,有没有一种惯用的方式来编写在同一个对象上操作的COM代码,但是可以从STA和MTA线程调用?

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?

推荐答案

将COM对象接口放入全局接口表,让GIT处理您的编组。当任何线程请求COM接口时,GIT检查调用公寓并且将相应地提供直接指针或适当的代理。

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.

这在MSDN上有说明:

This is documented on MSDN:

访问公寓之间的接口

这篇关于如何从不同的公寓模型访问COM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆