Thank you Lakamraju, actually I've found the solution myself yesterday evening, but this article helped me also, because I didn't think about garbage collector relocation.
My solution is here:
#include "stdafx.h"
#include "stdio.h"
using namespace System;
using namespace System::Runtime::InteropServices;
class Native{
public:
void (*myEvent)(int i); Native(){
myEvent=NULL;
}
void fireEvent(int i){
if(myEvent!=NULL) myEvent(i); };
void setmyEventHandler(void (*func)(int i)){
myEvent = func; }
};
private delegate void myEventDelegate(int i);
public ref class Managed{
Native* nativeObject;
myEventDelegate ^ del;
GCHandle delH;
public:
void fireEventHandler(int i){
printf("EVENT FIRED %d\n",i);
};
Managed(){
nativeObject=new Native();
del = gcnew myEventDelegate(this, &Managed::fireEventHandler);
delH = GCHandle::Alloc(del);
System::IntPtr d1 = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(del);
nativeObject->setmyEventHandler(( void(*)(int))d1.ToPointer()); };
~Managed(){ nativeObject->setmyEventHandler(NULL);
delete nativeObject;
delH.Free();
}
void testEvent(){
nativeObject->fireEvent(1598);
}
};
int main(array<system::string xmlns:system="#unknown"> ^args)
{
Managed^ managedClass = gcnew Managed;
GC::Collect();
managedClass->testEvent();
return 0;
}</system::string>
The only problem with this solution is that we can "register" only one "event handler"... actually this is not an event, just a callback.
Thank you once again!