title: C++/CLI string interop
body: <p>I am working on a C++/CLI wrapper for a native c++ class. The C++/CLI wrapper is being used in a WPF application. I have encountered a weird problem when trying to marshal strings.</p>
  
  <p>The WPF application passes a <code>System::String</code> object to my wrapper. The wrapper then converts the <code>System::String</code> to a <code>std::string</code> that the native class expects. This all goes fine, but once I pass the string to the native object, it is empty.</p>
  
  <p>Here is some relevant code</p>
  
  <p><strong>WPF Event Handler (C#)</strong></p>
  
  <pre><code>private void tbInputConfig_TextChanged(object sender, TextChangedEventArgs e)
  {
      _OrionBasicApp.ConfigTemplateFile = tbInputConfig.Text;
  }
  </code></pre>
  
  <p><strong>Property In Wrapper Class (C++/CLI)</strong></p>
  
  <pre><code>void BasicApp::ConfigTemplateFile::set(String ^value)
  {
      std::string val = marshal_as&lt;std::string&gt;(value);
      _NativeApp-&gt;setConfigTemplateFile(val);
  }
  </code></pre>
  
  <p><strong>Native Code (C++)</strong></p>
  
  <pre><code>void Basic_App::setConfigTemplateFile(const std::string&amp; template_file)
  {
     m_gParams.configTemplateFile = template_file;
  }
  </code></pre>
  
  <p>So when I break in the WPF app and trace using the debugger, the String objects look fine, the <code>std::string val</code> marshaling looks good, but the parameter <code>template_file</code> in the <code>setConfigFile</code> function is an empty string. When I step out of the native function, I can see that the <code>std::string val</code> variable still looks fine. </p>
  
  <p>I have tried using <code>Marshal::StringToHGlobalAnsi</code> function, it produces the same result. I have tried changing the native function to take copy of the string instead of a reference, this produces an exception about an invalid block of memory (if requested I will post the exact message). I have tried allocating the string on the heap, no luck. </p>
  
  <p>Now for the kicker: The native code was compiled with Microsoft Visual Studio 2008, and the wrapper + wpf code was compiled with 2010. I hope this is not the problem because it will not be easy for us to migrate either codebase to the other version. </p>
  
  <p>Any ideas?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I was able to switch the native code over to visual studio 2010 and this did fix the problem. (why must microsoft make my life so difficult?) While I did make the system build, the lead on the project is giving me MAJOR hassles about this solution (he is concerned that it may not run correctly or that we will have to switch over dependent libraries).</p>
  
  <p>SO is there a solution to this problem that doesn't force me to switch visual studio version?</p>