how to pass java class instance as a parameter to JNI method?

前端 未结 1 1148
长情又很酷
长情又很酷 2020-12-09 19:33

I\'d like to pass java class object to JNI method, And I want to call few methods in JNI method like below.

Is there anyone who have some example like below?

相关标签:
1条回答
  • 2020-12-09 20:19

    Your method declaration:

    class MainJavaClass {
        native void JNIMethod(JavaClassParameter object);
    }
    

    means javah should generate a forward declaration like the following:

    JNIEXPORT void JNICALL Java_MainJavaClass_JNIMethod(JNIEnv* env, jobject mainJavaClass);
    

    In the implementation of that, you have a few things to do:

    Find JavaClassParameter

    Use FindClass, which takes a string name:

    jclass cls = env->FindClass("JavaClassParameter");
    

    Find javaMethodTobeCalledInJNI()

    Use GetMethodID, which takes the class to check, the string name of the method, and its signature. Since this is a void function with no arguments, its signature is just ()V:

    jmethodID method = env->GetMethodID(cls, "javaMethodTobeCalledInJNI", "()V");
    

    Call javaMethodTobeCalledInJNI()

    Use CallVoidMethod, which takes the object instance, the method ID, and any arguments (none in this case):

    env->CallVoidMethod(mainJavaClass, method);
    

    You should check for NULL results after each step; if you get a NULL back from one JNI function and pass it to another, you'll usually crash the JVM

    0 讨论(0)
提交回复
热议问题