user3693423 user3693423 - 3 months ago 10
Android Question

Access ArrayList's element from jni

I am working with android NDK, in java, i pass an arrayList to the method. It is look like:

public static native float[] computeFeatures(ArrayList<double[]> list);


i am using javah to generate header file and in C++, this method has converted into:

JNIEXPORT jfloatArray JNICALL Java_khoa_cspdemo_Main_computeFeatures(JNIEnv *env,
jclass jc, jobject obj);


Now, in C++ code, i want to access each element of ArrayList (list), how do i get this? Please help me! Thanks in advance!

Answer

This is a little bit of an oversimplification, but it should get you started. ArrayList's are just objects and you don't need to worry about the generics in JNI. Just find the methods you want to call, check and make sure JNI found them, and then make the call to that method id. The native arrays need to be converted to JNI via the GetDoubleArrayElements call. You should read though the doc for Get<PrimitiveType>ArrayElements Routines

JNIEXPORT jfloatArray JNICALL Java_khoa_cspdemo_Main_computeFeatures(JNIEnv *env, jclass jc, jobject obj) {
    jclass ArrayList_class = (*env)->FindClass(env, "java/util/ArrayList");
    ArrayList_add_id = (*env)->GetMethodID(env, ArrayList_class, "add", "(Ljava/lang/Object;)Z");

    const long int buf[] = { 0, 1, 2, 3, 42 };

    jboolean isCopy;
    jdouble *jbuf = (*jenv)->GetDoubleArrayElements(env, buf, &isCopy);

    (*env)->CallBooleanMethod(env, obj, ArrayList_add_id, jbuf);
...
    (*jenv)->ReleaseDoubleArrayElements(jenv, buf, jbuf, 0);


    return JNI_OK;
}