Search code examples
javac++java-native-interface

Should I call PushLocalFrame and PopLocalFrame when I call Java Method From C++?


Question 1: I have a java class with a static method:

class Test {
    static public void show (String value) {
        // dosomething with value 
    }
}

If I want call it from c++:

jstring value = env->NewStringUTF("Hello, World");
// ExceptionCheck after NewStringUTF.
env->CallStaticVoidMethod(the_jclass, the_jmethodID, value);
// ExceptionCheck after CallStaticVoidMethod.

Should I put PushLocalFrame before NewStringUTF and put PopLocalFrame after CallStaticVoidMethod to release local references?

Question 2:

I see the declaration of PopLocalFrame, it's:

jobject PopLocalFrame(JNIEnv *env, jobject result);

After reading the jni documents, I still can't understand why PopLocalFrame needs a result parameter and a return value. Could you give me a example to show it's existence value?


Solution

  • Should I put PushLocalFrame before NewStringUTF and put PopLocalFrame after CallStaticVoidMethod to release local references?

    In this particular case I don't see the point. You could just use DeleteLocalRef to delete your local reference instead of creating a new local reference frame.

    I still can't understand why PopLocalFrame needs a result parameter and a return value

    Say that you created a new local reference frame with PushLocalFrame and you want to delete all local references created on that frame except for one reference that you'd like to keep (e.g. you created some object that you want to return from your function).
    You achive this by passing the reference you want to keep to PopLocalFrame, and the value you get back is a reference to that object within the previous local reference frame (which now is the current one).