任何想法如何初始化从"混合"类实例指向方法的.NET委托?
我有'混合'这样的C++类:
class CppMixClass
{
public:
CppMixClass(void){
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
}
~CppMixClass(void);
void UpdateState(System::Object^ sender, DotNetClass::StateEventArgs^ e){
//doSmth
}
}
Run Code Online (Sandbox Code Playgroud)
DotNetClass在C#中实现,方法声明在委托中是可以的.此行生成错误:
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
error C2276: '&' : illegal operation on bound member function expression
Run Code Online (Sandbox Code Playgroud)
任何人都有关于问题的线索?也许coz CppMixClass类不是纯.NET(ref)类?
当UpdateHealthState是静态方法时,我得到了这个,但我需要指向实例方法的指针.
我试过像:
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(this, &UpdateHealthState);
Run Code Online (Sandbox Code Playgroud)
但这显然不起作用因为这不是.NET(ref)类(System :: Object)的指针(句柄).
ServiceStateEventHandler在C#中定义为:
public delegate void ServiceStateEventHandler(object sender, ServiceStateEventArgs e);
Run Code Online (Sandbox Code Playgroud)
Thanx读这个:)
我刚刚找到答案(当然是Nishant Sivakumar,人似乎对我所有的C++/CLI互操作相关问题都有答案):
http://www.codeproject.com/KB/mcpp/CppCliSupportLib.aspx?display=Print
答案位于"msclr/event.h"标头中,其中定义了本机类中委托的宏.
尼什的代码如下:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1509 次 |
| 最近记录: |