Following the code from here (
http://java.sun.com/docs/books/jni/html/
other.html), I've constructed my JNI_OnLoad function in the same
manner:
JavaVM* g_jvm = 0;
jclass g_jniClass;
jmethodID g_jniCallback;
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
{
JNIEnv* env;
jclass jcls;
g_jvm = jvm;
// Check JNI support
if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_4))
return JNI_ERR;
jcls = (jclass)(*env)->FindClass(env, "JNIInterface");
if (jcls == NULL)
return JNI_ERR;
g_jniClass = (jclass)(*env)->NewWeakGlobalRef(env, jcls);
if (g_jniClass == NULL)
return JNI_ERR;
g_jniCallback = (jmethodID)(*env)->GetStaticMethodID(env, jcls, "g",
"()V");
if (g_jniCallback == NULL)
return JNI_ERR;
LOG_INFO("JNI_OnLoad completed!");
return JNI_VERSION_1_4;
}
JNI_OnLoad seems to run through correctly as I get the "JNI_OnLoad
completed!" in the LogCat. Later on, in another jni function I try to
invoke the callback using the cached jclass with this call:
JNIEXPORT void JNICALL callbackTest(JNIEnv *env, jobject obj)
{
(*env)->CallStaticVoidMethod(env, g_jniClass, g_jniCallback);
}
which results in the warning:
JNI WARNING: jclass points to invalid object 0xde5e3ff7
and the app crashes afterwards. Is it not possible to cache a jclass,
as this article seems to suggest (
http://android.wooyd.org/
JNIExample/)? Or am I perhaps invoking the callback incorrectly?