复制与JNI一个字节的缓冲区 [英] Copying a byte buffer with JNI
问题描述
我发现很多的StackOverflow是处理从C / JNI端复制字符数组变得像Java中的byte []的教程/的问题,而不是周围的其他方式。
I've found plenty of tutorials / questions on Stackoverflow that deal with copying char arrays from C/JNI side into something like a byte[] in Java, but not the other way around.
我使用的是本地C库,预计一个字节数组。我只是想从Java中的byte []的获取数据,为preferably C中的无符号字符[]。
I am using a native C library which expects a byte array. I simply want to get data from a byte[] in java, into preferably an unsigned char[] in C.
长话短说:什么是从jBytearray JNI中复制数据的最佳方式?有什么方法来检测它的大小?
Long story short: What is the best way of copying data from a jBytearray in JNI? Is there any way to detect it's size?
推荐答案
下面是一个工作的例子,我只是从我的AS / 400 JNI库举起来解决本地用户队列指针来测试队列的存在 - 它复制队列库并从Java字节数组(已转换为作业CCSID)到本机code的名字,并使用它。请注意释放函数调用的;这些是可以改变的,以本地阵列内容复制回到Java字节阵列来移动数据的其他方式:
Here's a working example I just lifted from my AS/400 JNI library to resolve a native user-queue pointer to test the queue's existence - it copies the queue library and name from a Java byte array (already translated to job's CCSID) into native code and uses it. Take note of the release function calls; these can be changed to copy the native array contents back into the Java byte arrays to move data the other way:
JNIEXPORT jboolean JNICALL Java_com_mycompany_jni400_UserQueue_jniResolve(JNIEnv *jep,jobject thsObj,
jbyteArray queueLibrary,jbyteArray queueName) {
jbyte *lib,*nam;
bool rtn;
thsObj=thsObj;
lib=(*jep)->GetByteArrayElements(jep,queueLibrary,0);
nam=(*jep)->GetByteArrayElements(jep,queueName,0);
rtn=(usrq_resolve((byte*)lib,(byte*)nam)!=NULL);
(*jep)->ReleaseByteArrayElements(jep,queueLibrary,lib,JNI_ABORT); /* abort to not copy back contents */
(*jep)->ReleaseByteArrayElements(jep,queueName ,nam,JNI_ABORT); /* abort to not copy back contents */
if(rtn) { return JNI_TRUE; }
else { return JNI_FALSE; }
}
这篇关于复制与JNI一个字节的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!