将COM接口指针传递给函数

Passing COM interface pointers to functions

本文关键字:函数 指针 COM 接口      更新时间:2023-10-16

我希望有人能帮我解决这个问题。我也希望这个问题有一个简单的答案。我觉得我错过了一些显而易见的东西,但我是C++的新手,一直无法克服这个问题。

我想将IUpdateCollection传递给函数,将IUpdates放入集合中,然后能够访问函数之外的集合。在下面的代码中,所有内容都在编译/运行,但在Searcher函数内部,IUpdateCollection中的项计数为5,但当我稍后尝试从函数外部计数IUpdateCollection的项时,计数为0。

我在这里错过了什么?

谢谢!

class W
{
public:
    // constructor
    W()
    {       
        //create the COM object to return the IUpdateSession interface pointer
        hr = CoCreateInstance( )
    }
    int Searcher(IUpdateCollection* pUpdateCollection)
    {                           
        //put the updates into our pUpdateCollection
        hr = pSearchResult->get_Updates(&pUpdateCollection);
        if(FAILED(hr) || pUpdateCollection == NULL)
        { cout << "Failed to put updates in the collection"; return -103; };
        long lUpdatesCount = NULL;
        hr = pUpdateCollection->get_Count(&lUpdatesCount);
        if(FAILED(hr) || pSearchResult == NULL)
        { cout << "Failed to get count of udpates in collection"; return -104; };
        cout << lUpdatesCount << endl;  //console outputs the actual count here, which at the moment is 5
        pUpdateSearcher->Release();     
        return 0;
    }
private:
    HRESULT hr;
    IUpdateSession* pUpdateSession; 
};
int main(int argc, char* argv[])
{
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    HRESULT hr;

    W myW;
    //pass the pUpdateCollection to the W.Searcher function
    myW.Searcher(pUpdateCollection);
    //get count of updates in collection
    long lUpdatesCount = NULL;
    pUpdateCollection->get_Count(&lUpdatesCount);
    cout << lUpdatesCount << endl;  //console outputs 0 here instead of the same count that it outputted in W.Searcher().  WHY?
    CoUninit();
    system("pause");
    return 0;
}

使用像_com_ptr_t_bstr_t这样的智能指针。使用原始指针并直接操作BSTR只不过是一种痛苦。

#import调用COM DLL将为您创建类型化的智能指针,包括易于使用的CreateInstance方法。智能指针还消除了在每次调用后明确检查HR的需要,它们会引发异常。

至于您的问题:这取决于COM对象的实现/规范/文档。也许发布IUpdateSearcher可以澄清这一点,但这只是我的猜测。相关代码将是COM服务器,而不是客户端。

没有注意到这是WUA,记录的行为

ISearchResult::Updates分配IUpdateCollection。因此,您要传入指针的值,在函数范围内对其进行更改,然后期望更改在范围外应用。与您正在做的事情完全相同,但使用int:

void f(int a)
{
  a=5;
}
void main()
{
  int a = 7;
  f(a);
  printf("%d", a); -- of course is 7, not 5
}

您可以通过传递ref或指针来解决int的"问题"。同样适用于COM指针。使用_com_ptr_t会清楚地显示问题:)

Updates属性返回一个IUpdateCollection指针,该指针将pUpdateCollection参数的内容覆盖到Searcher()方法。您在Searcher中检查的计数就是该集合的计数。

但是您通过值传递了pUpdateCollection,因此当您退出Searcher时,由get_Updates()检索的IUpdateCollection将被丢弃。

要看到这一点,请在get_Updates()调用上放置一个断点,并在执行get_Updates调用时观察pUpdateCollection的值的变化。然后走出Searcher,注意main的pUpdateCollection中的值没有更改。