henryyao
henryyao

Reputation: 1818

why need to create a temp array for returning an array from jni to java

For the following code of creating a int array for java from jni , Why do we need to create a temp[] array, why cannot we just fill the result[] array and return it to the java. Is it because that java and jni should use different memory space thus two different pointers? If so, what's the purpose of that? Thanks

JNIEXPORT jintArray JNICALL Java_ArrayTest_initIntArray(JNIEnv *env, jclass cls, int size)
{
 jintArray result;
 result = (*env)->NewIntArray(env, size);
 if (result == NULL) {
     return NULL; /* out of memory error thrown */
 }
 int i;
 // fill a temp structure to use to populate the java int array
 jint temp[256];
 for (i = 0; i < size; i++) {
     temp[i] = 0; // put whatever logic you want to populate the values here.
 }
 // move from the temp structure to the java structure
 (*env)->SetIntArrayRegion(env, result, 0, size, temp);
 return result;
}

Upvotes: 3

Views: 2812

Answers (1)

The reason of that, is you can not modify directly objects from jinitArray as they are Java objects not C's.

In your example you create a C's array, and move it to Java structure. Same approach must be respected while you are changing array content. You need a accessor that will provide the C's array.

A example how to modify array using JNI.

JNIEXPORT jintArray JNICALL Java_SendArray_loadFile(JNIEnv *env, jobject obj, jintArray input) {

    // Convert incoming JNI jinitarray to C's native jint[]
    jint *inputArray = env->GetIntArrayElements(env, input, NULL); // if last param JNI_TRUE, then a copy is returned.

    if(NULL == inputArray) {
       return NULL ;
    }

    const jsize length = env->GetArrayLength(input);

    for (int i = 0; i < length; i++) {
        inputArray[n] = 0; //We can operate on native jinit[] elements.
    }

    // Convert the C's native jinit[] int JNI jinitarray
    env->ReleaseIntArrayElements(env, input, inputArray, 0); // 0 - copy back the content and free the `input` buffer

    return inputArray;
}

The reason of that is in Java array is a reference type similar to class. That is why you need to convert between JNI array and native array.

Note: Presented about example refer to int type. JNI define nine types of array eight for primitive types (boolean, short, char, byte, int, long, float, double) and another one for Object.

Reference:

Get< PrimitiveType>ArrayElements Routines

Java Programming Tutorial Java Native Interface

Accessing Java Arrays

Upvotes: 3

Related Questions