title: Android JNI - Reliable way to convert jstring to wchar_t
body: <p>In my Android JNI code, I need to convert jstring to wchar_t. The closest reference I found was <a href="https://stackoverflow.com/questions/68042/how-do-i-convert-jstring-to-wchar-t">How do I convert jstring to wchar_t *</a>. </p>
  
  <p>One can obtain jchar* and the length using the following code:</p>
  
  <pre><code>const jchar *raw = env-&gt;GetStringChars(string, 0);
  jsize len = env-&gt;GetStringLength(string);
  
  wchar_t* wStr = new wchar_t[len+1];
  </code></pre>
  
  <p>It seems I cannot use wcncpy to copy "raw" into "wStr." Although jchar is 2-bytes long,  wchar_t is 4 bytes long on all modern versions of Android OS.</p>
  
  <p>One option is to copy one character at a time in a for loop:</p>
  
  <pre><code>for(int i=0;i&lt;len;i++) {
      wStr[i] = raw[i];
  }
  wStr[len] = 0;
  </code></pre>
  
  <p>The other option would be to call env->GetStringUTFChars() and use iconv_* routines to convert to wchar_t type.</p>
  
  <p>Can someone please confirm if option 1 is valid? Hope I don't have to resort to option 2. Is there a better option? Regards.</p>