简体   繁体   English

将无符号字符数组转换为 jstring

[英]Converting an unsigned char array to jstring

I'm having issues trying to convert an unsigned char array to jstring.我在尝试将 unsigned char 数组转换为 jstring 时遇到问题。

The context is I'm using a shared c library from Java.上下文是我正在使用来自 Java 的共享 c 库。 So I'm implementing a JNI c++ file.所以我正在实现一个 JNI c++ 文件。 The function I use from the library returs a unsigned char* num_carte_transcode我从库中使用的函数返回一个unsigned char* num_carte_transcode

And the function I implemented in the JNI C++ file returns a jstring.而我在 JNI C++ 文件中实现的函数返回一个 jstring。

So I need to convert the unsigned char array to jstring.所以我需要将 unsigned char 数组转换为 jstring。

I tried this simple cast return (env)->NewStringUTF((char*) unsigned_char_array);我试过这个简单的演员return (env)->NewStringUTF((char*) unsigned_char_array);

But though the array should only contain 20 bytes, I get randomly 22 or 23 bytes in Java... (Though the 20 bytes are correct)但是虽然数组应该只包含 20 个字节,但我在 Java 中随机得到 22 或 23 个字节......(虽然 20 个字节是正确的)

EDIT1: Here some more details with example EDIT1:这里有一些更多细节与示例

JNIEXPORT jstring JNICALL Java_com_example_demo_DemoClass_functionToCall
  (JNIEnv *env, jobject, ) {
  // Here I define an unsigned char array as requested by the library function
  unsigned char unsigned_char_array[20];
  // The function feeds the array at execution
  function_to_call(unsigned_char_array);

  // I print out the result for debug purpose
  printf("result : %.*s (%ld chars)\n", (int) sizeof unsigned_char_array, unsigned_char_array, (int) sizeof unsigned_char_array);

  // I get the result I want, which is like: 92311221679609987114 (20 numbers)

  // Now, I need to convert the unsigned char array to jstring to return to Java
  return (env)->NewStringUTF((char*) unsigned_char_array);
  // Though... On debugging on Java, I get 21 bytes 92311221679609987114 (check the image below)
}

在此处输入图像描述

And sometimes I get 22 bytes, sometimes 23 ... though the expected result is always 20 bytes.有时我得到 22 个字节,有时是 23 个……尽管预期的结果总是 20 个字节。

The string passed to NewStringUTF must be null-terminated.传递给NewStringUTF的字符串必须以空值结尾。 The string you're passing, however, is not null-terminated, and it looks like there's some garbage at the end of the string before the first null.但是,您传递的字符串不是以空值结尾的,并且看起来在第一个空值之前的字符串末尾有一些垃圾。

I suggest creating a larger array, and adding a null terminator at the end:我建议创建一个更大的数组,并在最后添加一个空终止符:

JNIEXPORT jstring JNICALL Java_com_example_demo_DemoClass_functionToCall
  (JNIEnv *env, jobject recv) {
  unsigned char unsigned_char_array[20 + 1]; // + 1 for null terminator
  function_to_call(unsigned_char_array);    
  unsigned_char_array[20] = '\0'; // add null terminator

  printf("result : %s (%ld chars)\n", unsigned_char_array, (int) sizeof unsigned_char_array);

  return (env)->NewStringUTF((char*) unsigned_char_array); // should work now
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM