Sign in to follow this  
akaitora

Managed Delegate to unmanged function pointer...

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites

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)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this