C ++ / CLI - 管理类到C#事件

C ++ / CLI  - 管理类到C#事件

问题描述:

我有一个c ++类,触发一些方法,比如一个事件。

I have a c++ class that triggers some method like an event.

class Blah {

   virtual void Event(EventArgs e);
}

当方法被调用一个C#事件将被调用?

How can I wrap it so whenever the method is called a C# (managed) event will be called?

我想到继承该类并重载事件方法,然后以某种方式调用托管事件。
我不知道该怎么做。

I thought of inheriting that class and overloading the event method, and then somehow call the managed event. I'm just not sure how to actually do it.

#include <vcclr.h>

struct blah_args
{
    int x, y;
};

struct blah
{
    virtual void Event(const blah_args& e) = 0;
};

public ref class BlahEventArgs : public System::EventArgs
{
public:
    int x, y;
};

public ref class BlahDotNet
{
public:
    event System::EventHandler<BlahEventArgs^>^ ItHappened;
internal:
    void RaiseItHappened(BlahEventArgs^ e) { ItHappened(this, e); }
};

class blah_event_forwarder : public blah
{
    gcroot<BlahDotNet^> m_managed;

public:
    blah_event_forwarder(BlahDotNet^ managed) : m_managed(managed) {}

protected:
    virtual void Event(const blah_args& e)
    {
        BlahEventArgs^ e2 = gcnew BlahEventArgs();
        e2->x = e.x;
        e2->y = e.y;
        m_managed->RaiseItHappened(e2);
    }
};