-
Delegates in C++/CLI
Hi,
I have the following callback registration function in my Native dll
Code:
typedef void (*IpOptMsg)(LPARAM lParam, int ipoptMsg, LPARAM lParamStruct);
void NLPRegisterCallback( IpOptMsg fnMsg);
And in my managed C++ code I write,
Code:
public ref class LibWrap
{
public:
delegate void EvaluateObjective(IntPtr lParam, int ipoptMsg, IntPtr lParamStruct);
[DllImport("demo.dll", CallingConvention = CallingConvention::Cdecl)]
static void IpOptNLPRegisterCallback(IntPtr lParam, EvaluateObjective^ fnMsg, IntPtr lParamStruct);
};
int main(array<System::String ^> ^args)
{
LibWrap::EvaluateObjective^ evalObjective;
LibWrap::IpOptNLPRegisterCallback(handle,evalObjective, IntPtr::Zero);
}
I don't get any compilation error, my after running my code I get an exception saying the memory is corrupt.
In C# I do the same thing as - and it works fine!
Code:
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate void EvaluateObjective(IntPtr lParam, uint ipoptMsg, IntPtr lParamStruct);
[DllImport("demo.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern void IpOptNLPRegisterCallback(IntPtr lParam, EvaluateObjective fnMsg, IntPtr lParamStruct);
Thanks in advance!
-
Re: Delegates in C++/CLI
LibWrap::EvaluateObjective^ evalObjective;
LibWrap::IpOptNLPRegisterCallback(handle,evalObjective, IntPtr::Zero);
You pass null reference evalObjective to IpOptNLPRegisterCallback. You need to assign some function to it.
In any case, you need to use Marshal.GetFunctionPointerForDelegate Method. Your code may fail if GC moves class instance which owns callback function. GetFunctionPointerForDelegate takes care about this.