gpt4 book ai didi

java - JNI : converting jstrings longer than 87 characters returns random characters

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:24 24 4
gpt4 key购买 nike

我正在使用 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
`¢¶

有人能告诉我为什么会发生这种情况和/或如何解决它吗?

最佳答案

不要这样做:

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

来自JNI documentation对于 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 之后引用该内存将导致未定义的行为.

关于java - JNI : converting jstrings longer than 87 characters returns random characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31201417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com