Search code examples
javac++arraysjava-native-interface

jni jiniArray as output parameter doesn't change values of parameter


I'm trying to call java static method from c++ program, I've got this java code:

public static int[] arrayFunc(int [] array) {
    int [] newArray = copyOf(array, array.length);
    for(int i = 0; i < newArray.length; ++i) {
        newArray[i] += 1;
    }
    return newArray;
}

Then in cpp code I have:

// JNIEnv *env is created before I call function
jintArray CallStaticFunction(const char* functionName, const int* parameter, const size_t size) {
    jmethodID mid = env->GetStaticMethodID(cls, functionName, "([I)[I");
    for(size_t i=0;i<size;++i) {
        printf("parameter = %d\n", parameter[i]);
    }
    if (mid) {
        jintArray iarr = env->NewIntArray(size);
        env->SetIntArrayRegion(iarr, 0, size, parameter);
        jintArray array = (jintArray)env->CallStaticObjectMethod(cls, mid, iarr);
        return array;
    } else {
        printf("find statis int method failed\n");
        exit(3);
    }
}

And in main.cpp I've:

env = ... //all the jvm initializatin work
int buf[3];
for(int i=0;i<3;++i){
    buf[i] = i;
}
jintArray ret = CallStaticFunction("arrayFunc", buf, 3);
for(int i=0;i<3;++i){
    printf("%d\n", ret[i]);
}

The output is:

parameter = 0
parameter = 1
parameter = 2
0
0
0

I expected that the last 3 lines should be "1 2 3". But actually not. So where did I get wrong in my program, and how to fix it?

Thanks a lot.


Solution

  • You can't access a jintArray as a regular C array. You need to use the appropriate JNI functions to gain access to the data:

    jintArray ret = CallStaticFunction("arrayFunc", buf, 3);
    int *p = env->GetIntArrayElements(ret, NULL);
    for(int i=0;i<3;++i){
        printf("%d\n", p[i]);
    }
    env->ReleaseIntArrayElements(ret, p, JNI_ABORT);
    

    Refer to the documentation for more details on how these functions work.