COM 使用 CoMarshalInterThreadInterfaceInStream 封送接口

COM using CoMarshalInterThreadInterfaceInStream to marshal interface

本文关键字:接口 CoMarshalInterThreadInterfaceInStream 使用 COM      更新时间:2023-10-16

我有一个在C++中注册函数和接口的方法,我正在使用CoMarshalInterThreadInterfaceInStream来封送指向另一个线程中方法的接口指针。

RegisterFunction

HRESULT hr = CoMarshalInterThreadInterfaceInStream(IID_Function, function, &stream);

GetFunction中发布它:

HRESULT hr = CoGetInterfaceAndReleaseStream(stream, IID_Function, reinterpret_cast<void**>(&function));

由于我将多次调用GetFunction并且CoGetInterfaceAndReleaseStream只释放一次流,因此如何保存流以再次使用它?


我尝试使用IGlobalInterfaceTable,但我无法让它工作。

我在RegisterFunction年成功注册了Inteface:

DWORD dwCookie = 0;
int a = 0;
if (pGIT == NULL) {
  HRESULT hr = CoCreateInstance(CLSID_StdGlobalInterfaceTable,
     NULL,
     CLSCTX_INPROC_SERVER,
     IID_IGlobalInterfaceTable,
     (void **)&pGIT);
  if (hr != S_OK) {
     throw _com_error(hr);
  }
}
if (dwCookie == 0) {
  HRESULT hr = pGIT->RegisterInterfaceInGlobal(function, IID_Function, &dwCookie);
  if (hr != S_OK) {
     throw _com_error(hr);
  }
}

但是当我试图在GetFunction中检索它时:

   IGlobalInterfaceTable* GIT = NULL;
      if (GIT == NULL) {
         hr = CoCreateInstance(CLSID_StdGlobalInterfaceTable,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_IGlobalInterfaceTable,
            (void **)&GIT);
         if (FAILED(hr)) {
            exit(0);
         }
      }
      hr = pGIT->GetInterfaceFromGlobal(dwCookie, IID_Function, (void**)&function);
      if (FAILED(hr)) {
            exit(0);
      }

当我尝试注册接口InGlobal时,我收到一个HR错误invalidArg(即使它使用与CoMarshalInterThreadInterfaceInStream相同的参数,除了cookie(

正如SoronelHaetil所说,你不能用CoMarshalInterThreadInterfaceInStream做到这一点。它只能(取消(封送接口一次。

看看改用IGlobalInterfaceTable。可以在表中注册一次 COM 对象,然后根据需要多次从任何线程/单元中的表中检索该对象,直到从表中撤消该对象。

你不能用CoMarshalInterThreadInterfaceInStream来做到这一点,它是一种方便的接口指针方法,只需提取一次。

相反,请使用CoMarshalInterface/CoUnmarshalInterface,并使用使用ShCreateMemStream创建的流。