11

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?

class JavaClassParameter{
    void javaMethodTobeCalledInJNI(){
        ...java source...
    }
}

class MainJavaClass{
    void somemethod(){
        JavaClassParameter object = new JavaClassParameter();
        JNIMethod(object);
    }

    native void JNIMethod(JavaClassParameter object);
}


// C++ code
void JNIMethod(object){
    object->javaMethodTobeCalledInJNI();
}
Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
howisgeek
  • 285
  • 2
  • 3
  • 9
  • 2
    If you want to pass a class object to a JNI method, you pass it like any other object. The code above appears to be passing instances of classes rather than classes, so I'm not sure how that relates to your question. – fadden Dec 17 '10 at 21:57

1 Answers1

14

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

oberthelot
  • 1,310
  • 1
  • 11
  • 23
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 2
    This might work if javaMethodTobeCalledInJNI() is a static method that is bound to the JavaClassParameter class. In this case it can use no instance field variables. The problem specifically states that object is to be passed as an instance argument to JNIMethod. Otherwise instance fields cannot be used. Since JNIMethod is a method of mainJavaClass, it would seem that Java_MainJavaClass_JNIMethod requires three arguments: env, the mainJavaClass implicit argument, and an explicit jobject JavaClassParameter_instanceObj. No? – DragonLord Jul 17 '17 at 15:08
  • also here you're defining the method ID with javaMethodTobeCalledInJNI which is underneath the JavaClassParameter class, but you're invoking it with an instance of mainJavaClass. I don't get it. – DragonLord Jul 17 '17 at 15:13