JNI:转换长度超过 87 个字符的 jstrings returns 个随机字符

JNI: converting jstrings longer than 87 characters returns random characters

我正在使用 JNI,我需要将一个 jstring 解析为一个 const char*,它工作正常,直到我传入一个长度超过 87 个字符的字符串。这是 Java 代码:

final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('.');
for(int i = 86; --i >= 0;) {
    stringBuilder.append('a');
}
System.out.println(stringBuilder.length()); //I used this to check the length until I got to the point where it would start returning random characters.
myFunction(stringBuilder.toString()); //It's not actually called myFunction.

这是 C++ 代码:

const char* keyPathNative = env->GetStringUTFChars(keyPath, JNI_FALSE);
env->ReleaseStringUTFChars(keyPath, keyPathNative);
std::cout << keyPathNative << std::endl;

我只收录了相关的部分。这是输出:

88
Ð0~

如果我再次执行相同的代码,它会给出不同的输出:

88
`¢¶

谁能告诉我为什么会这样and/or如何解决?

不要这样做:

env->ReleaseStringUTFChars(keyPath, keyPathNative);
std::cout << keyPathNative << std::endl;

来自 JNI documentation for GetStringUTFChars:

Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding. This array is valid until it is released by ReleaseStringUTFChars().

keyPathNative 指向的内存可能在 ReleaseStringUTFChars 之后被释放,因此在 ReleaseStringUTFChars 之后尝试引用该内存将导致未定义的行为。