Java – C Error JNI Access Object Array

C Error JNI Access Object Array… here is a solution to the problem.

C Error JNI Access Object Array

I

have an Android project that uses a C++ library and I need to send an array of objects to my C++ code.

This is my Java native binding (bind) code

class MyLib {
    public static native void testArray(String[] array);
}

That’s how I called it

...
MyLib.testArray(new Object[20]);
...

Here is my C++ jni code:

JNIEXPORT void JNICALL Java_com_android_mypackage_MyLib_testArray(JNIEnv * env, jobjectArray arr) {
    __android_log_print(ANDROID_LOG_INFO,"test","test array!!!!!!!!");
    int count = env->GetArrayLength(arr);
    __android_log_print(ANDROID_LOG_INFO,"test","array length %d", count);
     for (int i=0; i<count; i++) {
        __android_log_print(ANDROID_LOG_INFO,"test","--- get item %d", i);
        jstring jkey    = (jstring) env->GetObjectArrayElement(arr, i);
        __android_log_print(ANDROID_LOG_INFO,"test","item %d", i);    
        env->DeleteLocalRef(jkey);
    }
}

When I execute it, logcat shows this and the execution ends with sigsev 11

JNI WARNING: jarray arg has wrong type (expected array, got Ljava/lang/Class;) in Lcom/android/mypackage/MyLib;.testArray:([Ljava/lang/Object;)V (GetArrayLength)

Any idea why my array reference looks like a class reference? I have no problem with arrays of native type, only objects.

Solution

I trust your function signature

JNIEXPORT void JNICALL Java_com_android_mypackage_MyLib_testArray(JNIEnv * env, jobjectArray arr)

It should be like this:

JNIEXPORT void JNICALL Java_com_android_mypackage_MyLib_testArray(JNIEnv * env, jclass clazz, jobjectArray arr)

You are missing the second parameter – in a static method it is always a Class object.

Related Problems and Solutions