Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling DeleteLocalRef in java native interface

I'm returning a jstring from a JNI method. I delete the local reference to it before returning the value.

JNIEXPORT jstring JNICALL TestJNIMethod( JNIEnv* env, jclass )
{
    jstring  test_string = env->NewStringUTF( "test_string_value" );
    env->DeleteLocalRef( test_string );
    return test_string;
}

Would the calling JAVA method be still able to access the returned jstring or would the Garbage collector cleanup the memory?

like image 951
ssk Avatar asked May 18 '13 00:05

ssk


People also ask

What is the use of Java Native Interface JNI?

JNI is the Java Native Interface. It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++).

What is native method interface?

Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the Java virtual machine into native applications. The primary goal is binary compatibility of native method libraries across all Java virtual machine implementations on a given platform.

What is JNIEnv * env?

jobject NewGlobalRef(JNIEnv *env, jobject obj); Creates a new global reference to the object referred to by the obj argument. The obj argument may be a global or local reference.


1 Answers

No it will not, however your code will work on Android versions earlier than ICS. From ICS on this code will correctly fail.

In general you don't need to delete local references yourself, once the JNI function returns to Java the references will get GC'd.

The exception to that rule is if you create a lot of them, perhaps in a loop. Then it is possible to fill the local reference table. See IBM: Overview of JNI object references.

You should read JNI Local Reference Changes in ICS. Even if you are not writing for Android, it still identifies many common mistakes.

like image 126
Eoin Avatar answered Oct 02 '22 15:10

Eoin