Search code examples
c++event-handlingc++-cli

Raise .NET event from one DLL to another in C++/CLI


I have a native C++ application and two dll written in C#. Let's says that the native C++ application is 'AnApp' and the two dll are 'RaiseEvent'.dll and 'HandleEvent'.dll
Each of the two C# dll contains a class. RaiseEvent launch an event and HandleEvent subscribe to this event in order to execute a method called 'ReceiveEvent'.

In AnApp, there is a C++/CLI class that serves as a wrapper. In this wrapper, I instantiate an object from RaiseEvent and another from HandleEvent.
Then, the event is launched (I can see it in the debugger). I was expecting the event to be handled in the HandleEvent class, but it didn't happens. I mean, it never enter in the ReceiveEvent method.

I made all of this as a proof of concept, I was not sure that it was supposed to work.

So, the question is, is it possible to handle an event from one .NET dll to another when each dll are used in a native C++ application through a C++/CLI wrapper?


Solution

  • Its difficult to understand your exact problem without seeing some sample code, but I'll have a go.

    Instantiating the objects is not enough to link the event to the event handler. The event must be subscribed via the += operator

    var raiseEvent = new RaiseEvent();
    var handleEvent = new HandleEvent();
    raiseEvent.TheEvent += handleEvent.ReceiveEvent;
    

    I wouldn't recommend publicly exposing ReceiveEvent function like this. But the HandleEvent object needs access to the TheEvent instance in order to subscribe it.

    Maybe something like:

    class HandleEvent
    {
        //...
    
        public void Subscribe(RaiseEvent eventRaiser)
        {
            eventRaiser.TheEvent += this.ReceiveEvent;
        }
    }
    
    //...
    
    var raiseEvent = new RaiseEvent();
    var handleEvent = new HandleEvent();
    handleEvent.Subscribe(raiseEvent);