gpt4 book ai didi

java - JNI 错误 : accessed stale weak global reference

转载 作者:太空宇宙 更新时间:2023-11-03 10:18:23 24 4
gpt4 key购买 nike

我在我的 native 代码中缓存了对 Java 对象的引用,就像这样:

// java global reference deleter
// _JAVA_ENV is an instance of JNIEnv that is cached globally and just
// valid in current thread scope
static void g_java_ref_deleter(jobject ptr) {
_JAVA_ENV->DeleteGlobalRef(ptr);
}

// native class caches a java object reference
class NativeA {
private:
shared_ptr<_jobject> M_java_object;
public:
setJavaObject(jobject obj) {
M_java_object = shared_ptr<_jobject>(_JAVA_ENV->NewGlobalRef(obj), g_java_ref_deleter);
}

shared_ptr<_jobject> getJavaObject() const {
return M_java_object;
}
}

然后我在另一个本地类中访问它:

class NativeB {
public:
void doSomething(NativeA& a) {
// here I got an error: accessed stale weak global reference
// make_record do something on java object (set float field actually)
make_record(a.getJavaObject().get());
}
}

此代码在 Android 4.3 上运行。为什么会出现此错误,我该如何解决?

最佳答案

好的,我已经解决了这个问题!实际上我缓存了 _JAVA_ENV 并错误地使用了它。从这个blog我发现:

Although any given JNIEnv* is only valid for use on one thread, because Android never had any per-thread state in a JNIEnv*, it used to be possible to get away with using a JNIEnv* on the wrong thread. Now there’s a per-thread local reference table, it’s vital that you only use a JNIEnv* on the right thread.

所以我认为我缓存 JNIEnv 并在一个线程中使用它没有问题,但实际上当程序进入 java 环境时 JNIEnv 是陈旧的并且回到原生环境。 (呃……原谅我蹩脚的英文)

并且来自 documentation ,我发现:

If a piece of code has no other way to get its JNIEnv, you should share the JavaVM, and use GetEnv to discover the thread's JNIEnv.

因此,您应该缓存 JavaVM,并使用它来获取 JNIEnv,代码如下:

JavaVM* g_jvm;

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
g_jvm = vm;
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}

// Get jclass with env->FindClass.
// Register methods with env->RegisterNatives.

return JNI_VERSION_1_6;
}

JNIEnv* getJNIEnv() {
JNIEnv* env;
g_jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6 /*version*/);
return env;
}

希望能帮到别人! (请再次原谅我糟糕的英语..)

关于java - JNI 错误 : accessed stale weak global reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30993239/

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