I have started learning JNI to call C/Objective C from Java.
I have a simple java class like this where int i is declared and assigned within the setValue method:
// --------JAVA CLASS EXAMPLE 1
public class Test {
private native void _start();
private void setValue(string str) {
int i;
i = 6;
System.out.println(str);
}
}
The corresponding C/Objective C code does a callback to Java using CallStaticVoidMethod.
// ----------------JNI function in Objective C
JNIEXPORT void JNICALL Java_org_test_try__start
(JNIEnv * env, jobject obj){
JNF_COCOA_ENTER(env);
jobject myObject = (*env)->NewGlobalRef(env, obj);
jclass myClass = (*env)->GetObjectClass(env, myObject);
jmethodID myMethod = (*env)->GetMethodID(env, myClass, "setValue", "(Ljava/lang/StringV");
char* str = "Confirmed";
jstring js = (*env)->NewStringUTF( env, str );
(*env)->CallStaticVoidMethod(env, myClass, myMethod, js);
JNF_COCOA_EXIT(env);
}
This all works fine.
However, if I declare the int i in the java class and not inside the method as follows, the JVM crashes.
// --------JAVA CLASS EXAMPLE 2
public class Test {
private int i;
private native void _start();
private void setValue(string str) {;
i = 6;
System.out.println(str);
}
}
It SEEMS the callback can't access the int variable when it is declared at class level.
Why is this and how can I fix that?