user3796318 user3796318 - 17 days ago 12
Java Question

Returning bytebuffer from jni is copy or reference?

I am returning the bytebuffer from jni to java layer.

getData(JNIENV, *env, jobject obj ) {

pthread_mutex_lock(&mutexA);


while(dataAvailable == 0){
pthread_cond_wait (&cond, &MutexA);
}

dataAvailable = 0;

pthread_mutex_unlock(&MutexA);

return jnv->NewDirectByteBuffer(DataPointer, dataSize);
}


From Java :

while (1) {
ByteBuffer byteBuffer = getData();

}


Does this byteBuffer is referenced to the DataPointer, or, does it copy to 'byteBuffer' variable in the java layer ?

Answer

Java guide NewDirectByteBuffer

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.

Native code that calls this function and returns the resulting byte-buffer object to Java-level code should ensure that the buffer refers to a valid region of memory that is accessible for reading and, if appropriate, writing. An attempt to access an invalid memory location from Java code will either return an arbitrary value, have no visible effect, or cause an unspecified exception to be thrown.