Pregunta

I have a system comprising a C# UI, a C++/CLI mixed mode interop wrapper, and some native c++ projects.

What I need to do is set up a system such that the native c++ code can send a log message, and the UI can report it.

I set up a native IObservable using this as a template, but then the C# code can't be an observer. My thought was to set up another observer pattern in C++/CLI, which observes the native observer, and to let the C# implement that. I used this as a template but I'm struggling to convert this into valid C++/CLI.

ref class Observable
{
public:
Observable(void);
virtual ~Observable(void);

event System::EventHandler^ SomethingHappened;

void DoSomething() {
    System::EventHandler^ handler = SomethingHappened;
    //if (handler != nullptr)
    //{
        handler(this, System::EventArgs::Empty);
    //}//null check not permitted in C++/CLI
};

Gives the error: C3918: requires SomethingHappened to be a data member. This is the MSDN page - but I can't identify what I'm doing wrong.

Any suggestions?

Thanks, Melanie

¿Fue útil?

Solución

You are trying to use C# syntax. Events work a little differently in C++/CLI, they have a raise accessor in addition to the add and remove accessor. In other words, a method that fires the event. The compiler auto-generates one if you don't provide your explicit version it. That makes raising the event very simple:

void DoSomething() {
    SomethingHappened(this, System::EventArgs::Empty);
}

Otros consejos

In C++/Cli, you do not need to check the event for null (and you can't) when using "trivial events". The language takes care of that for you.

See related: Error C3918: Error wile checking event for being nullptr Does C++/CLI event have any listeners?

So, for your case, just remove the nullptr check

Using this, the right thing to do is to fire the event directly. Like this:

void DoSomething() {       
    SomethingHappened(this, System::EventArgs::Empty);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top