Managed Delegate to unmanged function pointer...

Started by
4 comments, last by mutex 14 years, 8 months ago
Hi guys. I keep getting a compile error that makes no sense to me. I am trying to convert a managed delegate to a function pointer. I am using the following msdn tutorial to do so. http://msdn.microsoft.com/en-us/library/367eeye0(VS.80).aspx The code I wrote looks like so in the header


delegate int GetTheAnswerDelegate(int, int);

int GetNumber(int n, int m) {
   Console::WriteLine("[managed] callback!");
   return n + m;
}
in my constructor I wrote the following

	GetTheAnswerDelegate^ fp = gcnew GetTheAnswerDelegate(&CubeTrisApp::FlashController::GetNumber);
The error I keep getting is Error 1 error C3352: 'int CubeTrisApp::FlashController::GetNumber(int,int)' : the specified function does not match the delegate type 'int (int,int)' However it looks like my GetNumber function matches my delegate. Any ideas? Thanks!

xdpixel.com - Practical Computer Graphics

Advertisement
You can't create a delegate around a native function; use Marshal.GetDelegateForFunctionPointer instead. (At least, I'm assuming we're looking at a native function here.)
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
GetNumber is not a native function. It is a member of a managed function.

xdpixel.com - Practical Computer Graphics

In that case, I think you should lose the address-of operator (&) and see what happens.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
GetTheAnswerDelegate^ fp = gcnew GetTheAnswerDelegate(CubeTrisApp::FlashController::GetNumber);


Taking the "&" out gets me the following error.

error C3867: 'CubeTrisApp::FlashController::GetNumber': function call missing argument list; use '&CubeTrisApp::FlashController::GetNumber' to create a pointer to member
1>.\FlashController.cpp(59) : error C3350: 'CubeTrisApp::FlashController::GetTheAnswerDelegate' : a delegate constructor expects 2 argument(s)

xdpixel.com - Practical Computer Graphics

gcnew GetTheAnswerDelegate(&CubeTrisApp::FlashController::GetNumber); requires that the GetNumber method be static. If it's an instance method you also need to pass the object reference:

using namespace System;delegate int GetTheAnswerDelegate(int, int);ref class TestClass{public:    TestClass()    {        GetTheAnswerDelegate^ fp = gcnew GetTheAnswerDelegate(this, &TestClass::GetNumber);    }    int GetNumber(int n, int m)    {        Console::WriteLine("[managed] callback!");        return n + m;    }};


Also, I hope you have a genuine reason for using C++/CLI such as the desire to interop with native components, otherwise you'll be in a world of awkwardness and oddities.

This topic is closed to new replies.

Advertisement