I have a direct ByteBuffer that should hold 15 double values created the following way
DoubleBuffer buff = ByteBuffer.allocateDirect(15*8).asDoubleBuffer();
I wanna access this buffer from native code and for the sake of simplicity just write the number from 1.0 to 15.0 in it. From the java side the method is
native public static void write(DoubleBuffer buff, int len);
and my C++ code is then
JNIEXPORT void JNICALL Java_ByteBufferTest_write(JNIEnv *env, jclass cl, jobject buff, jint len)
{
double* arr = (double*) env->GetDirectBufferAddress(buff);
for(int i=0; i<15; i++){
arr[i] = (double) i;
}
}
Calling the following in java
write(buff, 15);
for(int i=0; i<15; i++){
System.out.println(buff.get(i));
}
just prints garbage.
The question is, do I correctly allocate the DoubleBuffer? Would it be better to write
DoubleBuffer s = ByteBuffer.allocateDirect(15 * Double.SIZE/8).asDoubleBuffer();
or is there even a beter way?
The second question is, why is this not working? Is the cast to double* in the JNI code wrong?
Thanks
By default, Java’s XxxxBuffer is big endian. If you are using one of the Intel/AMD or some ARM processors it will be little endian by default.
Try using
BTW: Using nativeOrder() is usually faster as well. 😉