如何从 JNI、Java 和 C++ 中释放使用 jShortArray/jByteArray 分配的内存
How to free memory allocated with jShortArray/jByteArray from JNI, Java and C++
我正在尝试释放分配为虚拟变量的 t_data 的内存。 (代码如下)。现在,一旦我释放 t_data,程序就会抛出一个堆损坏错误,但是如果我将所有内容从 body 复制到 t_data 的新内存,则一切正常。删除代码在另一个 class 方法(此处未显示)中的某处调用,它仅使用 t_Data 指针来删除内存。
jshortArray val = (jshortArray)(m_pJVMInstance->m_pEnv->CallStaticObjectMethod(m_imageJ_cls, method_id, arr, (jint)t, (jint)c));
jsize len = m_pJVMInstance->m_pEnv->GetArrayLength(val);
jshort* body = m_pJVMInstance->m_pEnv->GetShortArrayElements(val, 0);
unsigned short int* dummy = reinterpret_cast<unsigned short int*>(body);
//t_data = dummy; //NOTE: Once you free t_data later exception is thrown.
t_data = new unsigned short int[len];
for (int i = 0; i < len; i++) {
unsigned short int test = *(body + i);
*((unsigned short int*)t_data + i) = test;
}
我正在尝试找出一种方法,无需 运行 for 循环即可将正文数据复制到 t_data,并且仍然能够释放内存。 (对于大图像,for 循环需要太多时间。)
迈克尔说的很对,确实解决了问题。参考他的评论:
Yes, definitely don't call free or delete on the pointer returned by GetShortArrayElements, because you don't know what GetShortArrayElements did internally. It might not have allocated any memory at all. Some implementations just pin the Java array to avoid having it moved by the GC, and then returns a pointer to the actual Java array contents. Just call ReleaseShortArrayElements when you're done with the pointer. – Michael
我正在尝试释放分配为虚拟变量的 t_data 的内存。 (代码如下)。现在,一旦我释放 t_data,程序就会抛出一个堆损坏错误,但是如果我将所有内容从 body 复制到 t_data 的新内存,则一切正常。删除代码在另一个 class 方法(此处未显示)中的某处调用,它仅使用 t_Data 指针来删除内存。
jshortArray val = (jshortArray)(m_pJVMInstance->m_pEnv->CallStaticObjectMethod(m_imageJ_cls, method_id, arr, (jint)t, (jint)c));
jsize len = m_pJVMInstance->m_pEnv->GetArrayLength(val);
jshort* body = m_pJVMInstance->m_pEnv->GetShortArrayElements(val, 0);
unsigned short int* dummy = reinterpret_cast<unsigned short int*>(body);
//t_data = dummy; //NOTE: Once you free t_data later exception is thrown.
t_data = new unsigned short int[len];
for (int i = 0; i < len; i++) {
unsigned short int test = *(body + i);
*((unsigned short int*)t_data + i) = test;
}
我正在尝试找出一种方法,无需 运行 for 循环即可将正文数据复制到 t_data,并且仍然能够释放内存。 (对于大图像,for 循环需要太多时间。)
迈克尔说的很对,确实解决了问题。参考他的评论:
Yes, definitely don't call free or delete on the pointer returned by GetShortArrayElements, because you don't know what GetShortArrayElements did internally. It might not have allocated any memory at all. Some implementations just pin the Java array to avoid having it moved by the GC, and then returns a pointer to the actual Java array contents. Just call ReleaseShortArrayElements when you're done with the pointer. – Michael