有没有办法通过JNI将Java数组传递给C而不复制它? [英] Is there any way to pass a Java Array to C through JNI without making a copy of it?

查看:99
本文介绍了有没有办法通过JNI将Java数组传递给C而不复制它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,使用GetDoubleArrayElements,JVM决定是否复制Array的元素。在这种情况下,有没有办法避免副本?如果没有,是否有其他方式从Java转移到C而不复制?我正在传递非常大的阵列,我希望我能避开副本。
谢谢

I understand that using GetDoubleArrayElements, it is the JVM who decides whether or not to copy the elements of Array. In this case, is there any way to avoid the copy? If not, is there an other way to transfer from Java to C without copying? I'm passing very big Arrays, and I wish I could avoid the copy. Thanks

推荐答案

JNI指南说:


在JDK / JRE 1.1中,程序员可以使用Get / ReleaseArrayElements函数来获取指向原始数组元素的指针。 如果VM支持固定,则返回指向原始数据的指针;否则,将复制。

JDK / JRE 1.3中引入的新功能允许本机代码获取指向数组元素的直接指针,即使VM不支持固定也是如此。

New functions introduced in JDK/JRE 1.3 allow native code to obtain a direct pointer to array elements even if the VM does not support pinning.

这些新功能是 GetPrimitiveArrayCritical ReleasePrimitiveArrayCritical 完全禁用垃圾收集,因此必须小心使用。总而言之,这是一个VM问题而不是API问题。不要忘记,如果没有固定垃圾回收器可能会决定压缩堆并物理移动你的数组,所以直接指针毕竟没什么用。

These "new functions" are GetPrimitiveArrayCritical and ReleasePrimitiveArrayCritical which disable garbage collection completely and have thus to be used with care. So in summary it is a VM problem rather than an API problem. Don't forget that without pinning the garbage collector might decide to compact the heap and physically move your array, so the direct pointer would be of little use after all.

As Peter建议您可以使用 java.nio.DoubleBuffer 而不是使用数组。 JNI函数

As Peter suggested you could work with a java.nio.DoubleBuffer instead of using arrays. The JNI function

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);

允许您访问它。

这篇关于有没有办法通过JNI将Java数组传递给C而不复制它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆