Skip to content Skip to sidebar Skip to footer

Jni Environment Pointer

I have a Java class in which I have a function which must be called from my C code. The function is the following: public void endTrial(){ //Code } So I have created the follo

Solution 1:

You cannot/should not store the JNIEnv pointer. Is is only valid for the current thread. But you can use AttachCurrentThread to get a JNIEnvpointer for your current thread. Or if you know that it is already attached you can use GetEnv. And beside of that you do not mention how you use the global jobject obj but keep in mind that you need to take care that those references stay valid long enough. NewGlobalRef is the way to go.

Untested:

JavaVM* g_jvm = 0;
JNIEXPORT void JNICALL package_initJNI(JNIEnv* en, jobject ob)
{
    ....
    // insted of the env store the VM
    en->GetJavaVM(&g_jvm);
    obj = en->NewGlobalRef(ob); // I don't think you need this// and at some point you must delete it again
    ....
}

JNIEXPORT void JNICALL package_endTrialJava(){
    JNIEnv* env;
    g_jvm->AttachCurrentThread(&env, NULL); // check error etc
    jobject javaObjectRef = env->NewObject(javaClassRef, javaMethodRef);
    // this line makes not much sense. I think you don't need it if you use the global// with the global it would be more like this
    env->CallVoidMethod(obj javaMethodRef);
}

Post a Comment for "Jni Environment Pointer"