Search code examples
c#eventsinteropdelegatescom-interop

Is there a way to call a C# delegate from COM Interop?


I'm porting a C# library to COM and I'm having a hard time trying to translate some delegates. The C# library works with some callbacks (using delegates). Usually I would translate that to events to be consumed by COM clients but the library only makes public Interfaces so I can not use the ComSourceInterfaces.

As an example of what I would like to be able to do:

[ComVisible(false)]
public delegate void ReceivedCOMMessageHandler (MessageCOM^ message);

[ComSourceInterfaces("ReceivedMessageEventInterface")]
public interface class IChannelCOM
{
    bool PushMessage (MessageCOM^ message);
    bool RegisterEventHandler (ReceivedCOMMessageHandler^ handler, FilterCOM^ filter);
    bool UnRegisterEventHandler (ReceivedCOMMessageHandler^ handler);
    property String^ Name;
    event ReceivedCOMMessageHandler^ ReceivedMessage;
};

[InterfaceType(ComInterfaceType::InterfaceIsIDispatch)]
[Guid("D4D2A638-303E-41d4-8925-07A2A60B17F3")]
public interface class ReceivedMessageEventInterface
{
    [DispId(1)] void ReceivedMessage(MessageCOM^ message);
};

I can't do this because the event is declared on a interface and the ComSourceInterface can only be declared in a class.

Any hints on what can I do to solve this problem?

EDIT: Another way of saying the same. Is there a way to declare events in interfaces rather than in classes in COM?

Thanks in advance.


Solution

  • As far as I've seen there is no way of doing that other than with Events and Events can only be thrown from a Class never from an Interface.