When Java is calling into a C function via JNI, we know that any local references to classes or objects may become invalid once the C function returns to java.
However when we only have C calling into Javam there is no "return to java". So it's not clear to me when these references will become invalid.
For example this is bad since aClass
, and anObject
will potentially become invalid once the call is complete.
jclass aClass;
jobject anObject;
JNIEXPORT void JNICALL Java_example_method1(JNIEnv *env) {
aClass = env->FindClass("AClass");
}
JNIEXPORT void JNICALL Java_example_method2(JNIEnv * env) {
jmethodID constructor = env->GetMethodID( aClass, "<init>", "()V");
anObject = env->NewObject(klass, constructor );
}
However in the following example, what can cause aClass
and anObject
to become invalid? Is it only an explicit call to DeleteLocalRef
?
jclass aClass;
jobject anObject;
int main() {
JavaVMInitArgs vm_args;
JavaVMOption options[1];
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
options[0].optionString = "-Djava.class.path=.";
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_FALSE;
JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
aClass = env->FindClass("AClass");
jmethodID constructor = env->GetMethodID( aClass, "<init>", "()V");
anObject = env->NewObject(klass, constructor );
}
That's correct. When Java calls JNI it allocates a table where local refs to, that are all released when the JNI returns. Wen you're calling Java there is no such mechanism.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments