Is there a way to pass a Java array to C via JNI without making a copy of it?

I understand that using GetDoubleArrayElements, it is the JVM that decides whether to copy the elements of the array or not. In this case, is there a way to avoid copying? If not, is there another way to port from Java to C without copying? I am transferring very large arrays and I would like to avoid copying. Thanks

+8
java jni
source share
1 answer

The JNI manual says:

In JDK / JRE 1.1, programmers can use the Get / ReleaseArrayElements functions to get a pointer to primitive elements of an array. If the VM supports binding, a pointer to the source data is returned ; otherwise a copy is made.

New features introduced in JDK / JRE 1.3 allow embedded code to get a direct pointer to array elements, even if the virtual machine does not support pinning.

These β€œnew features” are GetPrimitiveArrayCritical and ReleasePrimitiveArrayCritical , which completely block garbage collection and should therefore be used with care. So in summary, this is a VM problem, not an API problem. Do not forget that without fixing, the garbage collector may decide to compress the heap and physically move your array, so a direct pointer will be of little use in the end.

As Peter said, you can work with java.nio.DoubleBuffer instead of using arrays. JNI function

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

allows you to access it.

+4
source share

All Articles