1

我正在尝试订阅 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; 
        }
    }
}

由于文档(恕我直言)有点缺乏,我将自己定位于我在网上找到的一些代码示例。直到我称FindConnectionPoint一切正常。调用时,FindConnectionPoint我收到写入内存的访问冲突,所以我想问题出在我的IConnectionPoint指针上,它在我发现的多个代码示例中声明。

希望有更多监督的人能够帮助解决这个问题。提前致谢

4

1 回答 1

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,它实际上是在调用 1 的随机接口IMbnInterfaceManager方法

为了解决这个问题,需要将代码更改为:

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 这不是完全随机的。FindConnectionPointIConnectionPointContainer接口中的第二个条目,即v-table中的第五个条目(占3个IUnknown方法)。GetInterfaces方法IMbnInterfaceManager占据了相同的位置。它的第一个参数是一个 [out] 参数,因此可以解释写入时的访问冲突。

于 2016-09-08T15:40:00.310 回答