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.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值