我试图在android中使用JNI来创建一个函数指针,我使用的本机库使用它来调用java。
当调用initializeStateController
时,使用pthread_create
创建一个新线程,只要状态控制器的状态发生变化,它就会调用函数指针。
但是,当我尝试从C中的GetStaticMethodID
拨打state_exec
时,我收到以下错误:
JNI DETECTED ERROR IN APPLICATION: jclass is an invalid local reference: 0xec500019 (0xdead4321) in call to GetStaticMethodID
这是我目前的代码:
C代码
state_controller *controller;
JavaVM* gJvm = NULL;
static jclass sc_class;
JNIEnv* getEnv() {
JNIEnv *env;
int status = (*gJvm)->GetEnv(gJvm, (void**)&env, JNI_VERSION_1_6);
if(status < 0) {
status = (*gJvm)->AttachCurrentThread(gJvm, &env, NULL);
if(status < 0) {
return NULL;
}
}
return env;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pjvm, void* reserved) {
gJvm = pjvm;
JNIEnv *env = getEnv();
sc_class = (*env)->FindClass(env, "com/my/package/StateController");
return JNI_VERSION_1_6;
}
int state_exec(int state, int from) {
JNIEnv *env = getEnv();
jmethodID mid = (*env)->GetStaticMethodID(env, sc_class, "stateExec","(II)I");
jint result = (*env)->CallStaticIntMethod(env, sc_class, mid, state, from);
return (int) result;
}
// This part is unimportant.
// This is just where I hand the function pointer
// to the library to use.
JNIEXPORT void JNICALL
Java_com_my_package_StateController_initializeStateController
(
JNIEnv *env,
jobject jobj
) {
controller = new_state_controller(
state_exec
);
sc_start_controller(controller);
}
爪哇
package com.my.package;
class StateController {
public native void initializeStateController();
public static int stateExec(int state, int from) {
Log.d("StateTest", "State " + state + " -> " + from);
return 0;
}
}
. . .
(new StateController()).initializeStateController();
答案 0 :(得分:1)
事实证明FindClass
方法只返回本地引用,而不是全局引用。为了完成这项工作,您需要将其作为全局参考。你可以这样做,如下所示。
// Replace
sc_class = (*env)->FindClass(env, "com/my/package/StateController");
// With
sc_class = (*env)->NewGlobalRef(
env,
(*env)->FindClass(
env,
"com/my/package/StateController"
)
);
// Later when you are done with the class reference, run this to free it.
(*env)->DeleteGlobalRef(env, sc_class);
来自Android文档:
Bug:错误地假设FindClass()返回全局引用
FindClass()返回本地引用。很多人不这么认为。在没有类卸载的系统(如Android)中,您可以将jfieldID和jmethodID视为全局。 (它们实际上不是引用,但在具有类卸载的系统中存在类似的生命周期问题。)但是jclass是一个引用,而FindClass()返回本地引用。常见的错误模式是“静态jclass”。除非您手动将本地引用转换为全局引用,否则代码将被破坏。
https://android-developers.googleblog.com/2011/11/jni-local-reference-changes-in-ics.html