Search code examples
androidandroid-ndkjava-native-interface

returning unsigned character [] from the jni


I want to return the unsigned character [] from my jni method . I have following code in the Jni function :

unsigned char abc[16]
 abc[i] = 'b';

I have used jstring and jcharArray for returning the abc to the java code. But while using the jstring i am not able to compile the program correctly. anb while using the chararray i am getting some weird characters . Please suggest some solution how to deal with this problem.


Solution

  • The Java datatype that corresponds to C unsigned char is, in fact, byte. You need to declare your method as returning byte[] on the Java side, and act accordingly on the C side.

    Whether this is the right thing to do is another question. In C, "a string of text" and "an array of bytes" are pretty much synonyms (modulo null termination); in Java, not so. Is this a string of readable (ASCII) text? If it is, it is more natural to return it as a jstring; to convert from a C [unsigned] char * to a jstring, use JNIEnv::NewStringUTF(). But then there's another caveat: if your string is in a codepage other than UTF-8 and has non-ASCII characters (code >= 0x80), this won't work; then you're better off passing the string out as a byte array and converting it via the right codepage on the Java side.