如何从jni传递数组到java方法

时间:2015-11-18 20:25:56

标签: java android arrays callback java-native-interface

我正在尝试从int array传递JNI to Java。当我传递single or multiple intit works但传递array时无效。每次app崩溃并返回以下错误

错误

Invalid indirect reference 0x48609264 in decodeIndirectRef
Fatal signal 11 (SIGSEGV) at 0xdeadd00d....

JNI

jclass dataClass = env->FindClass("com/mypkg/project/DemoNative");
javaClassRef = (jclass) env->NewGlobalRef(dataClass);
javaMethodRef = env->GetMethodID(javaClassRef, "onDataReady", "([II)V");
jobject javaObjectRef = env->NewObject(javaClassRef, javaMethodRef);
jint array[2] = {1};
jintArray result;
result = env->NewIntArray(2);
env->SetIntArrayRegion(result,0,2,array);
env->CallVoidMethod(javaObjectRef, javaMethodRef,result,2);

的Java

public void onDataReady(int[] array,int len){
}

1 个答案:

答案 0 :(得分:0)

The line

jobject javaObjectRef = env->NewObject(javaClassRef, javaMethodRef);

is definitely wrong. It tries to use the method ID for onDataReady() as a constructor.

You probably need

jmethodID javaDefaultConstructor = env->GetMethodID(javaClassRef, "<init>", "()V");
jobject javaObjectRef = env->NewObject(javaClassRef, javaDefaultConstructor);

Note that jmethodID is not a reference: you can find the ID once and use it from any thread and on any instance you like. It's just a number, constant at least for the lifetime of your application.