title: Pass wchar_t strings from/to native plugin - only works on Windows?
body: <p>What I basically want to do is pass a <code>string</code> object to a native plugin and also get a <code>string</code> object back (not necessarily from/to the same function, but this doesn't matter after all).</p>
  
  <p>After quite some work I've settled to something like this (simplified example):</p>
  
  <pre class="lang-cpp prettyprint-override"><code>EXPORT const wchar_t* myNativeFunction(const wchar_t* param)
  {
      // Allocate the memory for the return value (to be freed by the Mono Runtime)
  #ifdef WIN32
      wchar_t *result = static_cast&lt;wchar_t *&gt;(CoTaskMemAlloc((result_length + 1) * sizeof(wchar_t)));
  #else
      wchar_t *result = static_cast&lt;wchar_t *&gt;(malloc((result_length + 1) * sizeof(wchar_t)));
  #endif
  
      // Here I'd copy the actual results with a length of 'result_length'
      return result;
  }
  </code></pre>
  
  <p>The C# backend in a Unity script looks like this:</p>
  
  <pre><code>[DllImport(nativeLibrary, EntryPoint = "myNativeFunction", CharSet = CharSet.Unicode)]
  [return: MarshalAs(UnmanagedType.LPWStr)]
  public static extern string myNativeFunction([MarshalAs(UnmanagedType.LPWStr)] string param);
  </code></pre>
  
  <p>When compiled and running under Windows this works just fine. I get the expected string to the native library and I get the correct string back, no matter whether there are non-ANSI characters in there or not.</p>
  
  <p>However, trying the same code under MacOS Sierra now, this doesn't seem to work properly. For simplification, I've shortened a test function to only return <code>L"Test"</code> copied to the output buffer (<code>result</code> in the example above). However, in Unity I receive a string <code>"T"</code> only.</p>
  
  <p>Overall, this looks like some weird encoding issue to me, but I can't nail it down. Did I miss anything?</p>
  
  <p><strong>Update:</strong> I've been able to identify the issue and it's indeed an encoding problem. Mono will <em>always</em> assume the width of <code>wchar_t</code> is 2 bytes (which it is on Windows), but this will break on Unix and MacOS, since these use <code>wchar_t</code>, which is 4 bytes wide. <strong>Looking for a neat solution that doesn't involve too much overhead.</strong></p>