Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

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

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...