带有非原始 jstring 参数的 ReleaseStringUTFChars?

ReleaseStringUTFChars with non-original jstring argument?

为了最小化 JNI 编组,我想通过设置方法在 C++ 端将一些字符串存储为静态变量,在不同的 JNI 方法调用中使用它们而不是每次都传递它们,然后释放字符串稍后使用另一个 JNI 方法调用。例如,

C++代码:

static const char *stringValue1;

extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_setValue1(JNIEnv* env, jclass jobj, jstring javaString) {
    jboolean isCopy;
    if(!env->IsSameObject(javaString, NULL)) {
        const char *stringValue1= env->GetStringUTFChars(javaString, &isCopy);
    }
}

extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_execute(JNIEnv* env, jclass jobj, jint javaInt) {
    // ... use the stringValue1 static variable - otherwise, this method would need another jstring argument.
}

extern "C" JNIEXPORT void JNICALL
Java_mypackage_myclass_releaseValue1(JNIEnv* env, jclass jobj, jstring javaString) {
    if(stringValue1 != 0) {
        env->ReleaseStringUTFChars(javaString, stringValue1);
    }
}

Java代码:

myclass.setValue1("hello")
for(int i = 0; i < 10; i++) {
    myclass.execute(i); // execute needs the "hello" string, but we try to store it in the C++ side rather than pass it in each loop iteration.
}
myclass.releaseValue1("hello");

这是有效的 JNI 模式吗?在我见过的所有 JNI 示例中,对 GetStringUTFCharsReleaseStringUTFChars 的调用都发生在同一个 method/scope 中。在此示例中,它们不出现在同一范围内,并且 jstring 参数可能也不相同 Java 字符串。

是,the documentation 状态

This array is valid until it is released by ReleaseStringUTFChars().

implementation in Hotspot 证实了这一点,它只是为副本分配了堆外内存。