How to create static JNI Environment Pointer?

后端 未结 2 744
日久生厌
日久生厌 2020-12-09 12:04

Here I create a class in JAVA in which I have function (callback) which I must call from C file.

class DSMInitializeClassParameter {

    /**
     * Callback         


        
2条回答
  •  孤城傲影
    2020-12-09 12:39

    It's generally unsafe to cache a JNIEnv* instance and keep using it, as it varies depending on the currently active thread. You can save a JavaVM* instance, which will never change. In a native initializer function, call GetJavaVM and pass it the address of a JavaVM pointer:

    static JavaVM *jvm;
    JNIEXPORT void JNICALL Java_SomeClass_init(JNIEnv *env, jclass) {
        int status = (*env)->GetJavaVM(env, &jvm);
        if(status != 0) {
            // Fail!
        }
    }
    

    Now you can use that JavaVM* to get the current JNIEnv* with AttachCurrentThread:

    dsmResult_t dsmInitializeCall( dsmResult_t status, void * pUserData, dsmEvent_t * hEvent ) {
        JNIEnv *env;
        (*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL);
        (*env)->CallVoidMethod(env, classObject, mid);
    }
    

提交回复
热议问题