下面是示例jni方法,我在其中创建一个字符串并将其返回给调用java方法:
jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
char test[100];
sprintf(test, "Test%03d.txt", rand()/100);
jstring returnVal = (*env)->NewStringUTF(env, test);
(*env)->DeleteLocalRef(env,returnVal);
return returnVal;
}
我希望jstring在调用java方法中无效,因为我删除了本地引用。但该参考仍然有效。我明确地调用System.gc()来查看GC是否清除它,但它没有发生。
根据这个:http://android-developers.blogspot.com/2011/11/jni-local-reference-changes-in-ics.html
"Bug: Calling DeleteLocalRef() and continuing to use the deleted reference
It shouldn’t need to be said that it’s illegal to continue to use a reference after calling DeleteLocalRef() on it, but because it used to work, so you may have made this mistake and not realized. The usual pattern seems to be where native code has a long-running loop, and developers try to clean up every single local reference as they go to avoid hitting the local reference limit, but they accidentally also delete the reference they want to use as a return value!
The fix is trivial: don’t call DeleteLocalRef() on a reference you’re going to use (where “use” includes “return”)."
我对这种不一致感到困惑。
答案 0 :(得分:2)
您定位的SDK级别是多少?如果您的目标是13或更低(ICS之前),那么您将获得旧的JNI行为,并且此代码应该可用(尽管它在技术上仍然不正确)
如果你的目标是14(ICS)或更高,那么显示的代码将失败并带有赠品错误:
memory map fault addr deadd00d
注意,如果您定位SDK 14+,但在早期版本的Android上运行应用程序,代码也会有用