I'm having issues trying to convert an unsigned char array to jstring.
The context is I'm using a shared c library from Java.
So I'm implementing a JNI c file.
The function I use from the library returs a unsigned char* num_carte_transcode
And the function I implemented in the JNI C file returns a jstring.
So I need to convert the unsigned char array to jstring.
I tried this simple cast 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)
EDIT1: Here some more details with example
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.
CodePudding user response:
The string passed to NewStringUTF
must be null-terminated. 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
}