16

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!

2 Answers 2

34

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

3
  • Do you get any exception? What is the return value you can see on the Java side? Oct 28, 2014 at 10:15
  • 1
    @DungQuang Please check the code now, I had some more time to look at it and fixed a rather embarrassing compiler error. The edited code works for me, and gives me back a byte array on the Java side with a count of six. Oct 28, 2014 at 21:35
  • tks, I resolved this problem by the code bellowing: JNIEXPORT jbyteArray JNICALL Java_com_example_json_bo_getArrray (JNIEnv *env, jobject o) { jbyte a[] = {1,2,3,4,5,6}; jbyteArray ret = (*env)->NewByteArray(env, 6); (*env)->SetByteArrayRegion (env, ret, 0, 6, a); return ret; } tks for help!
    – Dung Quang
    Oct 29, 2014 at 1:35
4

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;
}
1
  • 1
    You would need to call ReleaseByteArrayElements to release bytes when you are done.
    – Nat
    Oct 1, 2018 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.