Search code examples
c#cominteropiconnectionpoint

Connect to COM events in C# - support both managed and unmanaged servers


I'm writing C# code that needs to connect to COM events. I implemented the use of IConnectionPointContainer and IConnectionPoint thus:

      IConnectionPointContainer connectionPointContainer = internalGenerator as IConnectionPointContainer;
      if (connectionPointContainer == null)
      {
        Debug.Fail("The script generator doesn't support the required interface - IConnectionPointContainer");
        throw new InvalidCastException("The script generator doesn't support the required interface - IConnectionPointContainer");
      }
      Guid IID_IScriptGeneratorEvents = typeof(IScriptGeneratorCallback).GUID;
      connectionPointContainer.FindConnectionPoint(ref IID_IScriptGeneratorEvents, out m_connectionPoint);
      m_connectionPoint.Advise(this, out m_cookie);

The problem is that when the COM server is actually implemented in .Net (say, C#), after .Net creates it, it handles it as a .Net object, not a COM object. Since the .Net object doesn't implement the IConnectionPointContainer interface, I get null when trying to cast the object to that interface.

Any idea how can i workaround this? I can of course implement IConnectionPointContainer by myself in the C# COM server, however I would like a simpler solution, which I can easily explain to other developers which need to implement the COM server.

P.S I must use IConnectionPointContainer as the COM server may be implemented in non-.Net (C++, Java).

Thanks, Inbar


Solution

  • I didn't find a way to do this. Eventually I will define another interface in .Net and will write 2 code paths, one for .Net objects and one for real COM objects.