Any idea how to initialize .NET delegate that points to method from ‘mixed’ class instance?
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 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
Anyone have a clue about a problem? Maybe coz CppMixClass class is not a pure .NET (ref) class?
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);
But this obviously doesn’t work coz this is not pointer (handle) to .NET (ref) class, (System::Object).
ServiceStateEventHandler is defined in C# as:
public delegate void ServiceStateEventHandler(object sender, ServiceStateEventArgs e);
Thanx for reading this 🙂
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.codeproject.com/KB/mcpp/CppCliSupportLib.aspx?display=Print
Answer is located in ‘msclr/event.h’ header, where macros for delegates in native classes are defined.
Nish’s code is following: