title: P/Invoke with [Out] StringBuilder / LPTSTR and multibyte chars: Garbled text?
body: <hr>
  
  <p>I'm trying to use P/Invoke to fetch a string (among other things) from an unmanaged DLL, but the string comes out garbled, no matter what I try.</p>
  
  <p>I'm not a native Windows coder, so I'm unsure about the character encoding bits. The DLL is set to use "Multi-Byte Character Set", which I can't change (because that would break other projects). I'm trying to add a wrapper function to extract some data from some existing classes. The string in question currently exists as a CString, and I'm trying to copy it to an LPTSTR, hoping to get it into a managed StringBuilder.</p>
  
  <p>This is what I have done that I believe is the closest to being correct (I have removed the irrelevant bits, obviously):</p>
  
  <pre><code>// unmanaged function
  DLLEXPORT void Test(LPTSTR result)
  {
    // eval-&gt;result is a CString
    _tcscpy(result, (LPCTSTR)eval-&gt;result);
  }
  </code></pre>
  
  <hr>
  
  <pre><code>// in managed code
  [DllImport("Test.dll", CharSet = CharSet.Auto)]
  static extern void Test([Out] StringBuilder result);
  </code></pre>
  
  <hr>
  
  <pre><code>// using it in managed code
  StringBuilder result = new StringBuilder();
  Test(result);
  // contents in result garbled at this point
  </code></pre>
  
  <hr>
  
  <pre><code>// just for comparison, this unmanaged consumer of the same function works
  LPTSTR result = new TCHAR[100];
  Test(result);
  </code></pre>
  
  <p>Really appreciate any tips! Thanks!!!</p>