[Android Pro] 小心ReleaseByteArrayElements 中的參數問題


 

referen to : http://blog.csdn.net/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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM