title: C++ std::string to jstring with a fixed length
body: <p>I'm trying to turn a C++ std::string into a jstring and return it. This would be easy enough with</p>
  
  <pre><code>JNIEnv*-&gt;NewStringUTF(stdString.c_str())
  </code></pre>
  
  <p>but the problem is that the string I'm converting has almost randomly interspersed null characters in it. This is a problem for the <code>c_str()</code>, but not the <code>std::string</code>. <code>NewStringUTF</code> will only catch a portion of the full <code>std::string</code>. There is some hope in that the <code>std::string</code> has a <code>length()</code> function, which gets the full length, ignoring the problematic char* <code>\0</code> characters.</p>
  
  <p>There's a separate function <a href="https://docs.oracle.com/javase/jp/8/technotes/guides/jni/spec/functions.html#NewString">NewString</a> that takes in a jchar* and a jsize*, so that looks promising, but I can't get the std::string converted properly to the jchar*. I tried making it a byte array, but I probably wasn't doing it right. I had further problems converting the int given by the <code>length()</code> into a jsize, which was required by the NewString call. </p>
  
  <p>I have done a bit of work with <code>vector&lt;char&gt; byteArray(stdString.begin(), stdString.end())</code>, but that didn't get me very far, probably because that is messing up what the original string is.</p>
  
  <p>Here is the basic starter function I have, which worked with strings without null chars:</p>
  
  <pre><code>jstring StringToJString(JNIEnv * env, const std::string &amp; nativeString) {
      return env-&gt;NewStringUTF(nativeString.c_str());
  }
  </code></pre>
  
  <p>As a side note, this function is being used inside a JNI wrapper file for returning an object's <code>std::string</code>.</p>
  
  <p>Thanks for any help or information sources!</p>