How can I convert ArrayList <Integer> in Java to C ++ int array using JNI?

I am using JNI to call C ++ methods in my java client. In one of the methods, I am passing an ArrayList of integers and want to get an array of integers in C ++. When I pass ArrayList via JNI I get jObject. How do I convert this object to an array of integers?

I found this post similar but uses a string arraylist: JNI - Convert Java ArrayList to C ++ std :: string *

Any ideas on how to change which integers are used? I tried to just change std :: string refrences to int but no luck.

+3


source to share


1 answer


First make sure ArrayList <> is generic and JNI doesn't know anything about generics at all. Basically, for JNI, ArrayList <T> is ArrayList <Object>. Second, you are of course talking about ArrayList <Integer> and not ArrayList <int>, because the latter is not possible (see Why can't I have an int in the ArrayList type? ). Let's take a look at converting this to int [] in C ++. I'm not going to write code that compiles here because JNI is a huge tedious PITA, but it's the right idea, without any bloated error checking, you'll need it too; -)

FYI, anyone who names over 10 JNI methods starts looking for JNI wrapper generators for C ++. We wrote in-house ourselves, but I've heard that there are respectable open source and commercial tools.



jobject arrayObj = ...
jclass arrayClass = env->FindClass("java/util/ArrayList");
jmethodID sizeMid = env->GetMethodID(arrayClass, "size", "()I");
jclass integerClass = env->FindClass("java/lang/Integer");
jmethodID intValueMid = env->GetMethodID(integerClass, "intValue", "()I");
jvalue arg;
jint size = env->CallIntMethodA(arrayObj, sizeMid, &arg);
int* cppArray = new int[size];
jmethodID getMid = env->GetMethodID(arrayClass, "get", "(I)Ljava/lang/Object;");
for (int i = 0; i < size; i++) {
    arg.i = i;
    jobject element = env->CallIntMethodA(arrayObj, getMid, &arg);
    appArray[i] = env->CallIntMethodA(element, intValueMid, &arg);
    // you can't have an unlimited number of active local references.
    vm->DeleteLocalRef(element);
}

      

+3


source







All Articles