CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2009
    Posts
    4

    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!

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    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.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured