我正在尝试订阅MBN活动。这是我的代码:
void subscribeToMbnEvents()
{
dwError = CoInitializeEx(NULL, COINIT_MULTITHREADED);
SAFEARRAY* mbnInterfaces;
CComPtr<IMbnInterfaceManager> intMgr = NULL;
dwError = CoCreateInstance(CLSID_MbnInterfaceManager, NULL, CLSCTX_ALL, IID_IMbnInterfaceManager, (void**)&intMgr);
if (dwError != ERROR_SUCCESS)
{
CoUninitialize();
std::cout << getTimeStamp() << " failed to initialize IMbnInterfaceManager \n";
}
dwError = intMgr->GetInterfaces(&mbnInterfaces);
if (dwError != ERROR_SUCCESS)
{
CoUninitialize();
std::cout << getTimeStamp() << " failed to get MBN Interfaces \n";
}
if (dwError == ERROR_SUCCESS)
{
LONG indexOfFirstMBNInterface;
dwError = SafeArrayGetLBound(mbnInterfaces, 1, &indexOfFirstMBNInterface);
if (dwError != ERROR_SUCCESS)
{
std::cout << getTimeStamp() << " failed to get first index of MBN Interface \n";
}
CComPtr<IMbnInterface> MbnInt = NULL;
dwError = SafeArrayGetElement(mbnInterfaces, &indexOfFirstMBNInterface, (void*)(&MbnInt));
if (dwError != ERROR_SUCCESS)
{
std::cout << getTimeStamp() << " failed to get MBN Interface \n";
}
IConnectionPointContainer* icpc;
dwError = intMgr->QueryInterface(IID_IMbnInterfaceManager, (void**)&icpc);
if (dwError != ERROR_SUCCESS)
{
std::cout << "Error querying interface" << std::endl;
}
IConnectionPoint *icp;
dwError = icpc->FindConnectionPoint(IID_IMbnInterfaceEvents, &icp);
if (dwError != ERROR_SUCCESS)
{
std::cout << "Error finding connection point" << std::endl;
}
}
}
由于文档是(imho)有点缺乏我自己定位在网上找到的一些代码示例。直到我打电话给FindConnectionPoint
一切正常。当调用FindConnectionPoint
时,我得到一个访问冲突写入内存,所以我猜问题是我的IConnectionPoint
指针,在我找到的多个代码示例中声明。
希望有更多疏忽的人能够帮助解决这个问题。提前致谢
答案 0 :(得分:3)
检索IConnectionPointContainer
的代码是错误的:
IConnectionPointContainer* icpc;
dwError = intMgr->QueryInterface(IID_IMbnInterfaceManager, (void**)&icpc);
// ^^^^^^^^^^^^^^^^^^^^^^^^ wrong interface ID
if (dwError != ERROR_SUCCESS)
{
std::cout << "Error querying interface" << std::endl;
}
此代码返回IMbnInterfaceManager
接口,但会将其重新解释为IConnectionPointContainer
。当它继续执行icpc->FindConnectionPoint
时,它实际上是调用IMbnInterfaceManager
1 的随机接口方法。
要解决此问题,需要将代码更改为:
IConnectionPointContainer* icpc = nullptr;
HRESULT hr = intMgr->QueryInterface(IID_ConnectionPointContainer, (void**)&icpc);
if (FAILED(hr))
{
std::cout << "Error querying interface" << std::endl;
}
使用IID_PPV_ARGS宏更容易,更安全。它推导出与指针类型匹配的接口ID:
HRESULT hr = intMgr->QueryInterface(IID_PPV_ARGS(&icpc));
<小时/> 1 它并非完全随机。
FindConnectionPoint
是IConnectionPointContainer
接口中的第二个条目,即v表中的第五个条目(占3个IUnknown
方法)。 IMbnInterfaceManager
方法占用#main-content {
border: 50px solid #cc4242;
padding: 15px;
border-image-source: url('http://codeitdown.com/samples/zigzag_red.png');
border-image-slice: 10;
border-image-repeat: round;
}
中的相同位置。它的第一个参数是[out]参数,因此解释了写入时的访问冲突。