title: Converting from UTF-8 in C#
body: <p>I have a C++ library that generates some strings encoded using UTF-8. This library is consumed by a C# library that is able to access to the strings using a ddlexport. </p>
  
  <p>The C# code creates an StringBuilder and the C++ fills the characters in this object. But the characters that are not ASCII are impossible to be retrieved correctly. </p>
  
  <p>e.g: the string "ö" is encoded using two bytes with the codes 195 and 182, that corresponds with the codification of this character in UTF-8 (<a href="https://www.fileformat.info/info/unicode/char/00f6/index.htm" rel="nofollow noreferrer">0xC3 0xB6</a>). If I create the same string in C#, it is encoded using one byte with the code 246 that also corresponds with the codification for this character in Windows. </p>
  
  <p>I've tried to use the "Encoding.Convert" methods but I've been not able to convert the original string to the right encoded string. </p>
  
  <p>I've tried to reproduce the issue with this fragment of code:</p>
  
  <pre><code>StringBuilder str1 = new StringBuilder(2);
  str1.Append("ö");
  Console.WriteLine(str1.ToString());
  
  StringBuilder str2 = new StringBuilder(2);
  str2.Append((char)246);
  Console.WriteLine(str2.ToString());
  
  // This is the StringBuilder that I get from the C++ code
  StringBuilder str3 = new StringBuilder(2);
  str3.Append((char)195);
  str3.Append((char)182);
  Console.WriteLine(str3.ToString());
  
  byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, Encoding.UTF8.GetBytes(str3.ToString()));
  Console.WriteLine(Encoding.ASCII.GetString(bytes));
  </code></pre>
  
  <p>The output of this program is:</p>
  
  <pre><code>ö
  ö
  Ã¶
  ?? // bytes is 63, 63
  </code></pre>
  
  <p>How is possible to convert the UTF-8 code 0xC3 0xB6 (or 195 182) in the Windows code 246?</p>
  
  <p>EDIT:</p>
  
  <p>I've solved the problem with the answer of Marc Gravell just converting my StringBuilder to an array of bytes. But I wonder if the method that I'm using to pass strings between C++ and C# is wrong:</p>
  
  <p>The C++ code:</p>
  
  <pre><code> __declspec(dllexport)void Competitor_getDescription(ICompetitor *competitor, char *buf) {
     strcpy(buf, competitor-&gt;getDescription().c_str());
   }
  </code></pre>
  
  <p>The C#:</p>
  
  <pre><code> [DllImport(DLL)]
   private static extern void Competitor_getDescription(IntPtr obj, StringBuilder str);  
   public String GetDescription()
   {
      StringBuilder str = new StringBuilder(50);
      Competitor_getDescription(this.ptr, str);
      return str.ToString();
   }
  </code></pre>