Hooking a C# event from C++/CLI

不羁的心 提交于 2019-12-11 09:06:15

问题


So I have a C# class that has the following event:

public class CSClient
{
   public delegate void OnMessageHandler(Object sender, EventArgs e);
   public event OnMessageHandler OnOptionsEvent;
}

Then I have a C++/CLI class, for which I want to subscribe to OnOptionsEvent.

I have tried something like this:

void CSClientWrapper::Start()
{
   GCHandle h = GCHandle::FromIntPtr(IntPtr(_impl));
   CSClient^ obj = safe_cast<CSClient^>(h.Target);

   __hook(&CSClient::OnOptionsEvent, obj, &CSClientWrapper::OnOptions);
}

void CSClientWrapper::OnOptions(Object^ sender, EventArgs^ args)
{
}

error C2039: 'add_OnOptionsEvent' : is not a member of 'CSClient'

error C2750: 'CSClient::OnMessageHandler' : cannot use 'new' on the reference type; use 'gcnew' instead

I am completely new to C++CLI, so I suspect it is something really fundamental that I'm missing.


回答1:


Yes, that's not appropriate syntax. Best to forget that the __hook keyword exists, it was a fairly mistaken idea to add event handling syntax to native C++. You need to create a managed delegate to subscribe the event, correct syntax should be close to:

   CSClient^ obj = safe_cast<CSClient^>(h.Target);
   obj->OnOptionsEvent += 
      gcnew CSClient::OnMessageHandler(this, &CSClientWrapper::OnOptions);


来源:https://stackoverflow.com/questions/19386508/hooking-a-c-sharp-event-from-c-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!