I'm currently trying to combine a C # delegate with a pointer to a C ++ function, and I reviewed an example from Microsoft :
// MarshalDelegate1.cpp // compile with: /clr #include <iostream> using namespace System; using namespace System::Runtime::InteropServices; #pragma unmanaged // Declare an unmanaged function type that takes two int arguments // Note the use of __stdcall for compatibility with managed code typedef int (__stdcall *ANSWERCB)(int, int); int TakesCallback(ANSWERCB fp, int n, int m) { printf_s("[unmanaged] got callback address, calling it...\n"); return fp(n, m); }
A call to GCHandle :: Alloc () should prevent the garbage collector from collecting a delegate. But I understand that the variable GetTheAnswerDelegate ^ fp already keeps the delegate alive because it is the root object and is pretty sure even when I delete the calls in GCHandle, the example works. Only when I embed the delegate instance as follows:
IntPtr ip = Marshal::GetFunctionPointerForDelegate(gcnew GetTheAnswerDelegate(GetNumber));
then I see a crash.
So does the example from Microsoft look like, or did I miss something?
source share