将COM接口指针传递给函数

时间:2012-07-17 21:09:43

标签: c++ pointers

我希望有人可以帮助解决这个问题。我也希望这个问题有一个简单的答案。我觉得我错过了一些非常明显的东西,但我是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;
}

2 个答案:

答案 0 :(得分:1)

使用_com_ptr_t_bstr_t等智能指针。使用原始指针并直接操作BSTR只不过是痛苦。

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

关于你的问题:它取决于你的COM对象的实现/规范/文档。也许释放IUpdateSearcher可以清除数量,但这只是我的猜测。相关代码将是COM服务器,而不是客户端。

没有注意到这是用水户协会,记录在案的行为

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
}

你会解决问题&#39;通过ref或指针传递int。同样适用于您的COM指针。使用_com_ptr_t会清楚地显示问题:)

答案 1 :(得分:1)

Updates属性returns an IUpdateCollection pointer,它将pUpdateCollection参数的内容覆盖到Searcher()方法。您在Searcher内部检查的计数是该集合的计数。

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

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