Correct JNI_OnLoad JNI_OnUnLoad approach for cacheing jvm ref?
SreramJan 18 2012 — edited Jan 19 2012Currently am successful in calling a C API from Java. What am basically trying to do here is catch an event in C program, and callback the Java instance, to handle it in my Java code (Similar to a event handling in Swing).
I have implemented the event handling in Windows in C, and will be implementing it soon for Linux and Mac, but how do I cache jvm reference? As far as i searched in other forums, I realize the need for implementing JNI_OnLoad and JNI_OnUnLoad functions in C.
But am a bit confused in the concept of global references.
JavaVM *cached_jvm;
JNIEXPORT jint JNICALL myJavaClassCallback() {
jclass Class_myclass;
jmethodID MID_myclass_mymethod;
#ifdef JNI_VERSION_1_2
res = (*cached_jvm)->AttachCurrentThread(cached_jvm, (void**)&env, NULL);
#else
res = (*cached_jvm)->AttachCurrentThread(cached_jvm, &env, NULL);
#endif
if (res < 0) {
printf("Attach failed\n");
return;
}
Class_myclass = (*env)->FindClass(env, "mypackage.MyClass");
if (Class_myclass == NULL) {
goto detach;
}
MID_myclass_mymethod = (*env)->GetStaticMethodID(env, Class_myclass, "myMethod", "(Z)V");
if (MID_myclass_mymethod == NULL) {
goto detach;
}
jboolean jbool = JNI_FALSE;
(*env)->CallStaticVoidMethod(env, cls, MID_myclass_mymethod, jbool);//Correct?
detach:
if ((*env)->ExceptionOccurred(env)) {
(*env)->ExceptionDescribe(env);
}
(*jvm)->DetachCurrentThread(jvm);
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM jvm, void reserved) {
JNIEnv *env;
cached_jvm = jvm; /* cache the JavaVM pointer */
if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_2)) {
return JNI_ERR; /* JNI version not supported */
}
return JNI_VERSION_1_2;
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM jvm, void reserved) {
//Should i implement some delete reference here???
}
I have two questions here.
One, should i call some delete reference (or some function like deleteallrefereces (??)[if available]) on JNI_OnUnload?
And two is my passing of jboolean argument correct?
Thanks,
Sreram