简体   繁体   中英

assign jchararray to const unsigned char

I pass a char [] from java to jni :

function(char [] aChar);

then I read the char [] at jni :

JNIEXPORT jbyteArray JNICALL
packagename_function(JNIEnv *env, jobject obj, jcharArray aChar) {

  const unsigned char *theValue;
}

Now I want to assign aChar as a value for theValue.

What is the correct way to assign it?

You have two options here:

  1. You can pass array (as you do) and then, you need to retrieve it's elements:

    http://jnicookbook.owsiak.org/recipe-No-012/

     /* get size of the array */ jsize len = (*env)->GetArrayLength(env, array); /* get the body of array; it will be referecende by C pointer */ jchar *body = (*env)->GetCharArrayElements(env, array, 0); /* do some stuff */ for(int i=0; i < len; i++) { printf("Char value: %c\\n", body[i]); } /* release body when you decide it is no longer needed */ (*env)->ReleaseCharArrayElements(env, array, body, 0); 
  2. You can pass characters as a String object

    http://jnicookbook.owsiak.org/recipe-No-009/

     // we have to get string bytes into C string const char *c_str; c_str = (*env)->GetStringUTFChars(env, str, NULL); if(c_str == NULL) { return; } printf("Passed string: %s\\n", c_str); // after using it, remember to release the memory (*env)->ReleaseStringUTFChars(env, str, c_str); 

    In case of passing String from Java to C you have to change two things:

    • You need to change your method signature to

       packagename_function(JNIEnv *env, jobject obj, jstring aChar) 
    • In your Java code, you have to create String from characters

       char data[] = {'a', 'b', 'c'}; String str = new String(data); 

    and then, pass it to native code.

    Note! Be careful with types lengths! You can always check here:

    https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html

In java side, the char is encoding with UTF16, is counter part jni side is unsigned short not unsigned char, so i think if you want to set the java side char array to jni side, you have two options: 1. In java, convert the char array to byte array with UTF8 encoding. 2. Or in jni side, convert the UTF16 encoding string to UTF8 string. I think the previous option is more convenient.

Thanks to @mko for giving me the idea. My final code is :

/* get size of the array */
jsize len = (*env)->GetArrayLength(env, aChar);

/* get the body of array; it will be referecende by C pointer */
jchar *body = (*env)->GetCharArrayElements(env, aChar, 0);

jstring mystr =  (*env)->NewString(env, body, len);

/* release body when you decide it is no longer needed */
(*env)->ReleaseCharArrayElements(env, aChar, body, 0);

const unsigned char *theValue = (*env)->GetStringUTFChars(env,mystr, NULL);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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