C ++ / CLI - 管理类到C#事件 [英] C++/CLI - Managed class to C# events

查看:138
本文介绍了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);
    }
};

这篇关于C ++ / CLI - 管理类到C#事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆