title: How to marshall utf-8 string in C#
body: <p>The function in question is part of the native C API for Sqlite, but the answer should be general. I'm surprised I couldn't find an answer.</p>
  
  <p>The existing code looks like this, but just handles 8-bit ANSI.</p>
  
  <pre><code>// wrapper to handle marshalling and avoid nulls
  public static string sqlite3_column_text_wrapper(IntPtr pstmt, int iCol) {
    var ptr = sqlite3_column_text(pstmt, iCol);
    if (ptr == IntPtr.Zero) return "";
    else return Marshal.PtrToStringAnsi(ptr);
  }
  
  // wrapper to handle marshalling and avoid nulls // TODO: utf
  public static string sqlite3_column_text_wrapper_utf(IntPtr pstmt, int iCol) {
    var ptr = sqlite3_column_text(pstmt, iCol);
    if (ptr == IntPtr.Zero) return "";
    else return Marshal.PtrToStringAnsi(ptr);
  }
  
  [DllImport("sqlite3.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr sqlite3_column_text(IntPtr pstmt, int iCol);
  </code></pre>
  
  <p>The question is how to do the same thing for utf-8, preferably without having to allocate a buffer and copy the data twice.</p>
  
  <p>Surely there must be the "one best way"?</p>
  
  <hr>
  
  <p>I found this: <a href="https://stackoverflow.com/questions/12194828/c-sharp-callback-receiving-utf8-string">C# callback receiving UTF8 string</a>, which uses MultiByteToWideChar (twice) and StringBuilder. Might be the answer.</p>
  
  <hr>
  
  <p>An answer proposed an unsafe solution. This makes the app unverifiable, which is too high a price if any other solution is available. No unsafe please.</p>