title: How to pass a string from C++-CLI to C# via C++-CLI callbacks and delegates
body: <p>I have a C++-CLR wrapper around a standard C++ library called from C#.  To receive status messages from the library I use a delegate assigned to a callback in the C++ code via Marshal::GetFunctionPointerForDelegate.</p>
  
  <p>This has taken me quite some time to get working and I'm very, very close (I think).  The C# delegate is called but the string isn't passed correctly across the boundary.</p>
  
  <p>When I call TakesCallback("Test String") from the C++ code I just get rubbish back in the C# function.</p>
  
  <p>--- The original C++ class and callback function ---</p>
  
  <pre><code>class Solver
  {
      private:
  
      std::string TakesCallback(const std::string message) 
      {
          return cb(message);
      }
  
      public:
  
      // Declare an unmanaged function type that takes a string
      typedef std::string (__stdcall* ANSWERCB)(const std::string);
      ANSWERCB cb;
  };
  </code></pre>
  
  <p>--- Function to set the callback from the managed wrapper ----</p>
  
  <pre><code>// Set the delegate callback
  void ManagedSolver::SetMessageCallback(SendMessageDelegate^ sendMessageDelegate)
  {
      _sendMessage = sendMessageDelegate;
  
      // Use GetFunctionPointerForDelegate to get the pointer for delegate callback
      IntPtr ip = Marshal::GetFunctionPointerForDelegate(sendMessageDelegate);
      _solver-&gt;cb = static_cast&lt;Solver::ANSWERCB&gt;(ip.ToPointer());
  } 
  </code></pre>
  
  <p>--- C# function passed to the C++ \ CLR wrapper SetMessageCallBack ----</p>
  
  <pre><code>private void Message(string message)
  {
      XtraMessageBox.Show(message, "Done", MessageBoxButtons.OK);
  }
  </code></pre>