NDK ReferenceTable overflow (max=512) 问题

本文详细介绍了在JNI开发中如何避免ReferenceTableoverflow问题,通过正确使用和释放Java对象引用,包括FindClass、NewString、GetObjectField等操作的LocalRef管理,以及NewGlobalRef和DeleteGlobalRef的使用规范。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JNI层开发会遇到ReferenceTable overflow问题,特别是当jni函数被反复调用上千上万次的时候,现汇总如下

对于FindClass 返回的一定需要调用DeleteLocalRef,还有如下类型的变量需要DeleteLocalRef:

.FindClass /NewString/ NewStringUTF/NewObject/ GetObjectField等产生的都是LocalRef

总体原则:释放所有对object的引用。

1.FindClass

jclass ref= (env)->FindClass("java/lang/String");

env->DeleteLocalRef(ref); 

2.NewString/ NewStringUTF/NewObject/NewByteArray

jstring     (*NewString)(JNIEnv*, const jchar*, jsize);    

const jchar* (*GetStringChars)(JNIEnv*, jstring, jboolean*);     

void        (*ReleaseStringChars)(JNIEnv*, jstring, const jchar*);
jstring     (*NewStringUTF)(JNIEnv*, const char*);    

const char* (*GetStringUTFChars)(JNIEnv*, jstring, jboolean*);     

void        (*ReleaseStringUTFChars)(JNIEnv*, jstring, const char*);
env->DeleteLocalRef(ref);

3.GetObjectField/GetObjectClass/GetObjectArrayElement

jclass ref = env->GetObjectClass(robj);

env->DeleteLocalRef(ref); 

4.GetByteArrayElements

jbyte* array= (*env)->GetByteArrayElements(env,jarray,&isCopy);

(*env)->ReleaseByteArrayElements(env,jarray,array,0);

5.const char* input =(*env)->GetStringUTFChars(env,jinput, &isCopy);

(*env)->ReleaseStringUTFChars(env,jinput,input);

 

6.NewGlobalRef/DeleteGlobalRef

 jobject     (*NewGlobalRef)(JNIEnv*, jobject);     

void        (*DeleteGlobalRef)(JNIEnv*, jobject);

例如,

jobject ref= env->NewGlobalRef(customObj);

env->DeleteGlobalRef(customObj);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值