4
votes

I'm struggling to understand event handling when using COM. I have a COM object interface developed by a 3rd party that should fire some events. I need to handle these events from a C++ application. So far I have the following code to setup the event:

Event Setup (Main.cpp)

 IConnectionPointContainer* connection;
 result = comObjectInterface->QueryInterface(IID_IConnectionPointContainer, (void**)&connection);
 IConnectionPoint* connectionPoint;
 connection->FindConnectionPoint(__uuidof(_ICOMObjectInterfaceEvents), &connectionPoint);
 EventSink* sink = new EventSink();
 DWORD cookie = 0;
 connectionPoint->Advise(sink, &cookie);

My problem is that I don't know how to implement EventSink? I've seen people create a simple class that extends some form of IDispatch implementation but I don't seem to have this implementation available and I can't find any decent examples on how to create my own implementation. Currently I have two methods on my EventSink that I know get called:

EventSink.cpp

HRESULT __stdcall EventSink::QueryInterface(REFIID riid, void **ppv)
{
   *ppv = nullptr;
   HRESULT hr = E_NOINTERFACE;
   if (riid == IID_IUnknown || riid == IID_IDispatch ||
      riid == __uuidof(_ICOMObjectInterfaceEvents))
   {

      *ppv = static_cast<_ICOMObjectInterfaceEvents *>(this); //(static_cast<IDispatch*>(this));
      AddRef();
      hr = S_OK;
   }
   return hr;
}

ULONG __stdcall EventSink::AddRef()
{
   return InterlockedIncrement(&m_cRef);
}

I'm not sure if these methods a working correctly though.

Additionally, how can I debug this? I'm able to look inside the COM object code so I've been trying to find where the event is going to be generated from but I'm unable to find anything that logically looks like its going to produce an event.

1
Looks like a good start, and now you add actual IDispatch methods in EventSinkRoman R.

1 Answers

2
votes

I was having the same problem, and figured out a solution that works with Embarcadero C++ Builder. I put the info here: Is there a working example of COM event handling in C++ Builder?

I also include the .NET code to generate the COM object that generates events - a similar technique could be used to debug the event handling.