Convert wchar_t to Java String with JNI

I have a requirement to convert wchar_to Java String with JNI. There is no JNI API to do this job. So some code is needed. After some googling, I find this post http://forums.sun.com/thread.jspa?threadID=5279047 . It gives a long discussion about how to convert wchar_t to Java String. I uses the following code.

 

JNIEXPORT jstring JNICALL Java_TestJNI_getString
(JNIEnv * env, jclass cls) {
   const wchar_t* str = L"Here is a quite long and useless string. Note that this even works with non-ASCII characters, like in Allô les élèves.";
   size_t len = wcslen(str);
   if (sizeof(wchar_t) != sizeof(jchar)) {
      // In Linux, we get there.
      // First, allocate a buffer for the string to pass to Java, not forgetting the \0
      jchar* str2 = (jchar*)malloc((len+1)*sizeof(jchar));
      int i;
      for (i = 0; i < len; i++)
         // This discards two bytes in str[i], but these should be 0 in UTF-16
         str2[i] = str[i];
      str2[len] = 0;
      // Now we have a compatible string!
      jstring js = (*env)->NewString(env, str2, len);
      // And we can free the buffer, to prevent memory leaks
      free(str2);
      return js;
   }
   else
      // Under Windows, we don't need such a hack
      return (*env)->NewString(env, str, len);
}
 

But it does not work for my case. I am using JDK 1.6 on ubuntu 9.10. After some debugging, I find that I can just convert a wchar_t to wo jchar. http://en.wikipedia.org/wiki/Wchar_t give a description about wchar_t. If we want to produce portable C code, wchar_t should not be used.

 

 

你可能感兴趣的:(java,jdk,linux,jni,ubuntu)