如何在JNI中读取字节数组? [英] How to read a bytearray in JNI?
问题描述
是否可以在JNI中引用整个字节数组而不调用任何副本?
Is it possible to just reference a entire bytearray in JNI but not invoking any copy ?
在本机C代码中,我有一个从Java传递过来的字节数组,我只想比较一些数据到这个字节数组,所以我不想做任何内存复制。
In native C code, I have a bytearray passing from Java, and I just want to compare some data to this bytearray so I do not want to do any memory copy. Is it possible ?
我知道我可以通过使用GetPrimitiveArrayCritical之类的东西来获取本机字节数组的指针
I know I could get the pointer of a bytearray in native by using GetPrimitiveArrayCritical something like that
JNIEXPORT jbyteArray JNICALL Java_nfore_android_bt_pro_nfhfp_dsp
(JNIEnv *env, jobject jobj, jbyteArray jbIn, jbyteArray jbBase){
jbyte *bufferIn;
jbyte *bufferBase;
bufferIn = (*env)->GetPrimitiveArrayCritical(env, jbIn, NULL);
LOGD("Begin of dsp()");
LOGD("In dsp() Before Comparing...");
// Compare bufferIn with bufferBase here...
LOGD("In dsp() After Comparing...");
LOGD("End of dsp()");
(*env)->ReleasePrimitiveArrayCritical(env, jbIn, bufferIn, 0);
return jbIn;
}
如您所见,因为我可能会更改jbIn中的数据,应该使用GetPrimitiveArrayCritical来获取它的指针并在以后释放它。
As you could see, because I might change the data in the jbIn, I should use GetPrimitiveArrayCritical to get its pointer and release it later.
但是,如果我只想读取字节数组jbBase,我怎么能获得jbBase的指针却没有呢?使用GetPrimitiveArrayCritical吗?
However, if I just want to READ the bytearray jbBase, how could I get the pointer of the jbBase but not using GetPrimitiveArrayCritical ?
任何建议将不胜感激。非常感谢。
Any suggestion would be appreciated. Thanks a lot.
推荐答案
我使用以下内容读取字节数组...
I use the following to read byte arrays...
jbyte *b = (jbyte *)env->GetByteArrayElements(jbBase, NULL);
// read bytes in *b here
...
// release it
env->ReleaseByteArrayElements(jbBase, b, 0 );
您仍然需要释放它,因为这可能会阻止垃圾收集器在您仍在使用时将其清除使用它。
You still need to release it as that stops the Garbage collector getting rid of it potentially while you are still using it.
这篇关于如何在JNI中读取字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!