2
votes

I am a COM beginner and trying to use a managed library in my c++ project through COM.. I could able to create instance for the dual interfaces and call methods... it is working fine...

I would like to know how to construct client interface which can receive events from any dispinterface COM object ?

#include "stdafx.h"
#import "../COMLib/bin/Debug/COMLib.tlb" named_guids
#include <comutil.h>

int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);

COMLib::ICalcPtr pCalc;

HRESULT hRes = pCalc.CreateInstance(__uuidof(COMLib::Calc));
if(FAILED(hRes))
    printf("ICalcPtr::CreateInstance failed w/err 0x%08lx\n", hRes);
else
{
    printf("%d\n", pCalc->Factorial(10));
}

CoUninitialize();
return 0;
}

I know how to create instance for dual interface like above. But I need help to instantiate dispinterface for events. Your help is much appreciated.

1
"Working fine" - so what is the question? - MSalters
working for dual interface. Don't know how to create instance for a dispinterface. I have to receive events from the dispinterface. - user3077435
The trick with understanding COM is to be clear that you don't create an instance of an interface. You create an instance of a CoClass and then QueryInterface for whatever you need/the CoClass implements. You are not creating an instance of a dispinterface. You are accessing the dispinterface of an already created instance of something. - dkackman

1 Answers

1
votes

Once you have you Com instance just go ahead and queryinterface for any further interfaces you need to use. Assuming it implements IDispatch you'll have a pointer to that interface.

COMLib::ICalcPtr pCalc;

HRESULT hRes = pCalc.CreateInstance(__uuidof(COMLib::Calc));
if(FAILED(hRes))
    printf("ICalcPtr::CreateInstance failed w/err 0x%08lx\n", hRes);
else
{
    IDispatchPtr pDisp;
    hRes = pCalc->QueryInterface(IID_IDispatch, &pDisp);
    ASSERT(SUCCEEDED(hRes));

    printf("%d\n", pCalc->Factorial(10));

}

If you are looking to sink COM events from this object you probably really want the IConnectionPoint set of interfaces. This article has good explanation and examples of how to attach to and sink connection point events from COM objects in C++.