是否有可能对本机类消费.NET事件? [英] Is it possible for native class to consume .NET event?
问题描述
不知道如何初始化.NET委托指向方法从混合类的实例?
Any idea how to initialize .NET delegate that points to method from 'mixed' class instance?
我有'混'的C ++类是这样的:
I have 'mixed' C++ class like this:
class CppMixClass
{
public:
CppMixClass(void){
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
}
~CppMixClass(void);
void UpdateState(System::Object^ sender, DotNetClass::StateEventArgs^ e){
//doSmth
}
}
DotNetClass是用C#实现的,方法声明是代表确定。 此行生成错误:
DotNetClass is implemented in C#, and Method declaration is OK with delegate. This line generates error:
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
error C2276: '&' : illegal operation on bound member function expression
任何人有一个问题的线索? 也许怎么把CppMixClass类不是一个纯粹的.NET(REF)班?
Anyone have a clue about a problem? Maybe coz CppMixClass class is not a pure .NET (ref) class?
我得到这个工作的时候UpdateHealthState是静态方法,但我需要指针的实例方法。
I got this to work when UpdateHealthState is static method, but I need pointer to instance method.
我试过水木清华这样的:
I tried smth like:
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(this, &UpdateHealthState);
但是,这显然是行不通的堂妹这是不是指针(句柄)到.NET(REF)班,(系统:对象)。
But this obviously doesn't work coz this is not pointer (handle) to .NET (ref) class, (System::Object).
ServiceStateEventHandler在C#中定义为:
ServiceStateEventHandler is defined in C# as:
public delegate void ServiceStateEventHandler(object sender, ServiceStateEventArgs e);
感谢名单读这篇文章:)
Thanx for reading this :)
推荐答案
我刚刚找到答案,这(当然由NISHANT西瓦库玛,人类似乎已经回答我所有的C ++ / CLI互操作相关的问题):
I just found answer to this(of course by Nishant Sivakumar, man seems to have answers to all my C++/CLI interop related problems):
HTTP://www.$c$cproject。 COM / KB / MCPP / CppCliSupportLib.aspx?显示=打印
答位于msclr / event.h头,其中定义宏的本机类的代表。
Answer is located in "msclr/event.h" header, where macros for delegates in native classes are defined.
尼什的code为以下内容:
Nish's code is following:
class Demo5
{
msclr::auto_gcroot<FileSystemWatcher^> m_fsw;
public:
// Step (1)
// Declare the delegate map where you map
// native method to specific event handlers
BEGIN_DELEGATE_MAP(Demo5)
EVENT_DELEGATE_ENTRY(OnRenamed, Object^, RenamedEventArgs^)
END_DELEGATE_MAP()
Demo5()
{
m_fsw = gcnew FileSystemWatcher("d:\\tmp");
// Step (2)
// Setup event handlers using MAKE_DELEGATE
m_fsw->Renamed += MAKE_DELEGATE(RenamedEventHandler, OnRenamed);
m_fsw->EnableRaisingEvents = true;
}
// Step (3)
// Implement the event handler method
void OnRenamed(Object^, RenamedEventArgs^ e)
{
Console::WriteLine("{0} -> {1}",e->OldName, e->Name);
}
};
这篇关于是否有可能对本机类消费.NET事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!