I have the following JNI method that creates a collection of Java objects natively, and then return them to Java:
JNIEXPORT jobject JNICALL Java_com_test_myClass_myMethod(JNIEnv * env, jclass klass) {
jclass arrayClass = env->FindClass("java/util/ArrayList");
jmethodID initMethod = env->GetMethodID(arrayClass, "<init>", "()V");
jmethodID addMethod = env->GetMethodID(arrayClass, "add", "(Ljava/lang/Object;)Z");
jobject myArray = env->NewObject(arrayClass, initMethod);
env->CallBooleanMethod(myArray, addMethod, env->NewStringUTF("Hello"));
env->CallBooleanMethod(myArray, addMethod, env->NewStringUTF("World"));
return myArray;
}
Do I need to free the objects created in the native code, or is it done automatically by the GC? If I do, how do I do that, as I need to return it to Java?
You do not need to free the Java objects created in the native code. In fact, you cannot. The garbage collector may free the object when no further references remain.
Occasionally it is useful in native code to free references to Java objects. This can reduce memory requirements when the native code holds, but no longer needs, references to large objects or a large number of references.
From: "Global and local references" in the JNI specification.
Additional detail was provided See "Freeing References" in the JNI Programmer's Guide.