title: How to wrap UTF-8 encoded C++ std::strings with Swig in C#?
body: <p>My question is nearly identical to <a href="https://stackoverflow.com/questions/16749871/how-to-make-swig-deal-with-utf8-strings-in-c">this question</a>, except that the linked question deals with char*, whereas I'm using std::string in my code. Like the linked question, I'm also using C# as my target language.</p>
  
  <p>I have a class written in C++:</p>
  
  <pre><code>class MyClass
  {
  public:
      const std::string get_value() const; // returns utf8-string
      void set_value(const std::string &amp;value); // sets utf8-string
  private:
      // ...
  };
  </code></pre>
  
  <p>And this get's wrapped by SWIG in C# as follows:</p>
  
  <pre><code>public class MyClass
  {
      public string get_value();
      public void set_value(string value);
  }
  </code></pre>
  
  <p>SWIG does everything for me, except that it doesn't make an utf8 to utf16 string conversion during the calls to MyClass. My strings come through fine if they are representable in ASCII, but if I try passing a string with non-ascii characters in a round-trip through "set_value" and "get_value", I end up with unintelligible characters.</p>
  
  <p>How can I make SWIG wrap UTF-8 encoded C++ strings in C#? n.b. I'm using std::string, not std::wstring, and not char*.</p>
  
  <p>There's a partial solution on the <a href="http://sourceforge.net/p/swig/patches/249/" rel="nofollow noreferrer">SWIG sourceforge site</a>, but it deals with char* not std::string, and it uses a (configurable) fixed length buffer.</p>