Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return byte array in jni android?

I need get byte array from jni to Java. Ex: I have a byte array byte[] a = {1,2,3,4,5,6}

JNIEXPORT jbyteArray JNICALL Java_com_vn_getArray (JNIEnv *env, jobject obj) {
  jbyte[] a = {1,2,3,4,5,6};
  return a;

}

I do not know how to return a byte array from jni.

Can someone help me? Please!

like image 673
Dung Quang Avatar asked Oct 28 '14 07:10

Dung Quang


2 Answers

In Java, an array is an object. So to hand a byte array from C or C++ over to java you will need to instantiate a jbyteArray, and return that. Instead of a C array. To solve that, see the following code:

JNIEXPORT jbyteArray JNICALL Java_Test_returnArray
  (JNIEnv *env, jobject This)
{
        jbyte a[] = {1,2,3,4,5,6};
        jbyteArray ret = env->NewByteArray(6);
        env->SetByteArrayRegion (ret, 0, 6, a);
        return ret;
}

Based on this link

like image 105
TheDutchDevil Avatar answered Sep 19 '22 14:09

TheDutchDevil


I do like that and it's working

JNIEXPORT jbyteArray JNICALL Java_com_vn_getArray(JNIEnv *env, jobject obj) {
    jbyte byteUrl[] = {1,2,3,3,4};
    int sizeByteUrl = 5;

    jbyteArray data = (*env)->NewByteArray(env, sizeByteUrl);
    if (data == NULL) {
        return NULL; //  out of memory error thrown
    }

    // creat bytes from byteUrl
    jbyte *bytes = (*env)->GetByteArrayElements(env, data, 0);
    int i;
    for (i = 0; i < sizeByteUrl; i++) {
        bytes[i] = byteUrl[i];
    }

    // move from the temp structure to the java structure
    (*env)->SetByteArrayRegion(env, data, 0, sizeByteUrl, bytes);

    return data;
}
like image 28
Dung Quang Avatar answered Sep 19 '22 14:09

Dung Quang