将COM接口指针传递给函数
Passing COM interface pointers to functions
我希望有人能帮我解决这个问题。我也希望这个问题有一个简单的答案。我觉得我错过了一些显而易见的东西,但我是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会清楚地显示问题:)
但是您通过值传递了pUpdateCollection,因此当您退出Searcher时,由get_Updates()检索的IUpdateCollection将被丢弃。
要看到这一点,请在get_Updates()调用上放置一个断点,并在执行get_Updates调用时观察pUpdateCollection的值的变化。然后走出Searcher,注意main的pUpdateCollection中的值没有更改。
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针