raise events in c++/cli dll and consume in c#

2020-02-29 04:20发布

问题:

In my c# app I have a progressbar. C# app is calling a c++/cli dll which processes a number of files. As each file is processed in the dll I would like to track it's progress in the c# app. For this i need to raise an event in c++/cli and consume it in C#. From MSDN I gather I need in my c++/cli class the following:

  delegate void Del(int);
  event Del^ E;
  void fire(int i) {
      E(i);
   }

MSDN Events

In MSDN the receiver of the event is in the same c++/cli project and it is shown how to raise the event. In my project, the c# app is to receive the event which should be raised in c++/cli after each file is processed. I've googled a lot too but have not been able to figure it out yet. So, my question is, how do I raise this event in c++/cli, and how do I connect my c# program to it? Some code that shows the way to do it would be greatly appreciated. thanks!

Matt, thanks for responding. In C# I am trying

MW.Class1 oM = new MW.Class1();
oM.fire += ProgressBarChanged(int i);

It does not compile saying cannot assign because fire is a method group. I also have in my C# program, the handler

public void ProgressBarChanged(int i )
{

}

This does better though compiler says int is not expected and does not compile

oM.fire += new EventHandler(ProgressBarChanged(int i));

回答1:

As the error message says, fire is a method, not an event. Call += on the event, and leave off the () when you reference the event handler method.

oM.E += this.ProgressBarChanged;

As for firing the event, you're doing that correctly: Just call your event like a delegate or a method, passing the event arguments.



标签: c# c++-cli