[Android Pro] 小心ReleaseByteArrayElements 中的参数问题

在Android开发中,使用JNI的ReleaseByteArrayElements函数时需要注意最后一个参数。如果设置为0,它会释放指向的内存,可能导致栈上数组的随机错误。建议使用JNI_COMMIT以避免内存问题。

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

referen to : http://blog.youkuaiyun.com/rainlight/article/details/818964

在Sun的官方文档中,关于该函数的用法如下

The array is returned to the calling Java language method, which in turn, garbage collects the reference to the array when it is no longer used. The array can be explicitly freed with the following call.

  (*env)-> ReleaseByteArrayElements(env, jb, 
                                        (jbyte *)m, 0);

The last argument to the ReleaseByteArrayElements function above can have the following values:

  • 0: Updates to the array from within the C code are reflected in the Java language copy.

     

  • JNI_COMMIT: The Java language copy is updated, but the local jbyteArray is not freed.

     

  • JNI_ABORT: Changes are not copied back, but the jbyteArray is freed. The value is used only if the array is obtained with a get mode of JNI_TRUE meaning the array is a copy.

小心最后一个参数,如果为0是会释放 m 所指向的内存的. 如果M刚好指向一个栈上的数组的话,这样可能在Release 版本中造成内存方面的随机错误.可以用JNI_COMMIT来避免.

其实现代码也许如下

+void
+KaffeJNI_ReleaseByteArrayElements(JNIEnv* env UNUSED, jbyteArray arr, jbyte* elems, jint mode)
+{
+ BEGIN_EXCEPTION_HANDLING_VOID();
+
+ if (elems != unhand_array((HArrayOfByte*)arr)->body) {
+ switch (mode) {
+ case JNI_COMMIT:
+ memcpy(unhand_array((HArrayOfByte*)arr)->body, elems, obj_length((HArrayOfByte*)arr) * sizeof(jbyte));
+ break;
+ case 0:
+ memcpy(unhand_array((HArrayOfByte*)arr)->body, elems, obj_length((HArrayOfByte*)arr) * sizeof(jbyte));
+ KFREE(elems);
+ break;
+ case JNI_ABORT:
+ KFREE(elems);
+ break;
+ }
+ }
+ END_EXCEPTION_HANDLING();
+}


JNI_COMMIT forces the native array to be copied back to the original array in the Java virtual machine.JNI_ABORT frees the memory allocated for the native array without copying back the new contents

分类:  Android Pro
本文转自demoblog博客园博客,原文链接http://www.cnblogs.com/0616--ataozhijia/p/5624954.html如需转载请自行联系原作者

demoblog
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值