title: Return string from c++ function pointer invoked from c#
body: <p>I need to call a c++ callback function from c# that returns a String. When I try with the code below the application crashes hard (with a message saying that it may be due to a corruption of the heap).</p>
  
  <p>Here's the c++ code:</p>
  
  <pre><code>static String^ CppFunctionThatReturnsString()
  {
      return gcnew String("From C++");
  }
  
  void main()
  {
      CSharp::CSharpFunction(IntPtr(CppFunctionThatReturnsString));
  }
  </code></pre>
  
  <p>And here's the c# code:</p>
  
  <pre><code>public class CSharp
  {
      private delegate string CppFuncDelegate();
  
      public static void CSharpFunction(IntPtr cppFunc)
      {
          var func = (CppFuncDelegate)Marshal.GetDelegateForFunctionPointer(cppFunc, typeof(CppFuncDelegate));
          func(); // Crash
      }
  }
  </code></pre>
  
  <p>Do I have to do some kind of marshaling magic with the string before returning it?</p>