V-Xtreme
V-Xtreme

Reputation: 7333

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.

Upvotes: 1

Views: 2117

Answers (2)

Kirill Karmazin
Kirill Karmazin

Reputation: 6736

After I've done all the work in C++ I'm copying the data from a regular native byte array (actually it is unsigned char *dataB) to a new JNI object jbyteArray (same thing but for JNI) which can be returned back to Java code:

...
//Prepare jbyteArray to return to Java
jbyteArray resultReturn = env->NewByteArray(dataLength);
//copy data:
env->SetByteArrayRegion(resultReturn, 0, dataLength, reinterpret_cast<const jbyte *>(dataB));

    return resultReturn;
}  

where dataB is an array of bytes unsigned char *dataB which has all the data I worked with.

Upvotes: 0

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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.

Upvotes: 4

Related Questions