C++ Callback to send text back to C#

前端 未结 4 1881
有刺的猬
有刺的猬 2021-01-03 09:14

I\'m new to C++. I have been told using a \"callback\" with C++ is the best solution for this. Here is my situation.

I have a DLL written in C++
this DLL has

4条回答
  •  不知归路
    2021-01-03 10:18

    There may be cleaner ways, but here are some of the steps I used to make it work.

    Define the delegate and the function to pass it to your DLL. The parameters are what will be sent back to the C# delegate:

      public delegate uint CallbackFn( uint param1, uint param2 );
    
      [DllImport("yourdll.dll",  CallingConvention=CallingConvention.Winapi, EntryPoint="RegisterTheCallback" )]
      private static extern uint RegisterTheCallback( CallbackFn pfn );
    

    Create a variable to store the delegate. Make sure this doesn't go out of scope. In my testing, I found that the GC would reclaim it (it wasn't "aware" that my DLL was still using it):

      CallbackFn mCmdCallback = null;
    

    Then initialize it somewhere:

      mCmdCallback = new CallbackFn( YourCallback );
    

    And then pass it to your DLL:

    RegisterTheCallback( mCmdCallback );
    

    And define the actual method that will receive the call:

      private uint YourCallback( uint param1, uint param2 )
      {
        // report progress etc.
      }
    

    The code in the DLL might look like this:

    DWORD _declspec( dllexport ) WINAPI RegisterTheCallback
    (
       DWORD (WINAPI *lpfnCallback)( DWORD param1, DWORD param2 )
    )
    {
    // Store lpfnCallback somewhere so that it can be called later
    ...
    }
    

    And then the code in your DLL can call it with the appropriate data when it needs:

    ret = (lpfnCallback)( 234, 456 );
    

提交回复
热议问题