我正在从 java 调用 native 函数以返回一个字节 []。
以下是 JNI 代码片段
jbyteArray result;
jbyte *resultType;
result = (*env)->NewByteArray(env, 1);
*resultType =7;
(*env)->SetByteArrayRegion(env, result, 0, 1, resultType);
return result;
这应该创建一个长度为 1 的字节数组,并将值 7 存储在其中。我的实际代码应该创建一个动态长度的数组,但遇到了与本示例中相同的问题。
现在我的问题来了——在 java 中,从 JNI 返回的数组是空的。 我究竟做错了什么?任何帮助将不胜感激。
最佳答案
SetByteArrayRegion()
的原型(prototype)是:
void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
最后一个参数是一个内存缓冲区,SetByteArrayRegion()
会将其复制到 Java 数组中。
您永远不会初始化该缓冲区。你正在做:
jbyte* resultType;
*resultType = 7;
我很惊讶你没有得到核心转储,因为你正在将 7
写入内存中的某个随机位置。相反,这样做:
jbyte theValue;
theValue = 7;
(*env)->SetByteArrayRegion(env, result, 0, 1, &theValue);
更一般地说,
// Have the buffer on the stack, will go away
// automatically when the enclosing scope ends
jbyte resultBuffer[THE_SIZE];
fillTheBuffer(resultBuffer);
(*env)->SetByteArrayRegion(env, result, 0, THE_SIZE, resultBuffer);
或
// Have the buffer on the stack, need to
// make sure to deallocate it when you're
// done with it.
jbyte* resultBuffer = new jbyte[THE_SIZE];
fillTheBuffer(resultBuffer);
(*env)->SetByteArrayRegion(env, result, 0, THE_SIZE, resultBuffer);
delete [] resultBuffer;
关于java - 从 JNI 获取 java 中的空字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5804439/