Reputation: 2916
I made a very simple JNI application to fill an array. The C++ code should simply insert elements into the list. However, env->CallBooleanMethod
yields a segmentation fault. The input arguments to this method are all not null. As far as I understand, this should work. What's the problem of this?
public class Main {
public static void main(String[] args) {
System.load("/path/to/project/Main.so");
List<Integer> list = new ArrayList<>();
Main.fill(list, 1);
System.out.println(list);
}
private static native void fill(List<Integer> list, int n);
}
JNIEXPORT void JNICALL Java_Main_fill
(JNIEnv *env, jclass cls, jobject jList, jint jn) {
jclass jListCls = env->GetObjectClass(jList);
jmethodID jListAddMethod = env->GetMethodID(jListCls, "add", "(Ljava/lang/Object;)Z");
for (int i = 0; i < jn; i++) {
env->CallBooleanMethod(jList, jListAddMethod, (jint) i); // <- Segfault occurs here
}
env->DeleteLocalRef(jListCls);
}
Upvotes: 1
Views: 66
Reputation: 58467
Your list elements are of the type java.lang.Integer
. In JNI code there's no autoboxing, so primitive integers won't get automatically converted to java.lang.Integer
.
You'll have to get/create the java.lang.Integer
instances yourself. That is, get a reference to that class using FindClass
, get a reference to the static valueOf
method, and then invoke it.
Upvotes: 2