JNI returning Java 对象,return 本地引用是否可以,还是必须是全局的?

JNI returning Java object, is it OK to return local reference, or must it be global?

在 JNI 方法中说我想 return 一个 Java 字符串(或任何其他 Java 对象。)returned 对象可以是本地引用吗在该方法中创建,还是应该将 return 值转换为全局引用?

简单的例子:

extern "C"
JNIEXPORT jstring JNICALL Java_some_package_SomeObj_getStringTest(JNIEnv *env, jclass obj)
{
    return env->NewString("Test", 4); // OK to return local reference?
}

或者应该是:

extern "C"
JNIEXPORT jstring JNICALL Java_some_package_SomeObj_getStringTest(JNIEnv *env, jclass obj)
{
    jstring str = env->NewString("Test", 4);
    return env->NewGlobalRef(str); // Must return a global reference?
}

前者,我做到了。按预期工作。

来自JNI documentation

Global and Local References

The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.

Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its result.

所以,你的第一个例子是完全合法的:

extern "C"
JNIEXPORT jstring JNICALL Java_some_package_SomeObj_getStringTest(JNIEnv *env, jclass obj)
{
    return env->NewString("Test", 4); // OK to return local reference?
}