从 jni 返回字节缓冲区是复制还是引用?
Returning bytebuffer from jni is copy or reference?
我正在将字节缓冲区从 jni 返回到 java 层。
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);
}
来自 Java :
while (1) {
ByteBuffer byteBuffer = getData();
}
这个 byteBuffer 是否引用了 DataPointer,或者,它是否复制到 java 层中的 'byteBuffer' 变量?
是referenced to the DataPointer
,不是复制。所以在 Java ByteBuffer.
的生命周期中保持原生内存范围
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.
当然,您可以使用get(byte[] dst, int offset, int length)
从ByteBuffer中获取字节数组。
我正在将字节缓冲区从 jni 返回到 java 层。
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);
}
来自 Java :
while (1) {
ByteBuffer byteBuffer = getData();
}
这个 byteBuffer 是否引用了 DataPointer,或者,它是否复制到 java 层中的 'byteBuffer' 变量?
是referenced to the DataPointer
,不是复制。所以在 Java ByteBuffer.
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.
当然,您可以使用get(byte[] dst, int offset, int length)
从ByteBuffer中获取字节数组。