从JNI获取java中的空字节数组

从JNI获取java中的空字节数组,java,java-native-interface,Java,Java Native Interface,我正在从java调用本机函数以返回字节[]。 下面是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代码的一个片段

jbyteArray result;  
jbyte *resultType;  
result = (*env)->NewByteArray(env, 1);  
*resultType =7;
(*env)->SetByteArrayRegion(env, result, 0, 1, resultType);    
return result;
这将创建一个长度为1的字节数组,值7存储在其中。我的实际代码应该创建一个动态长度的数组,但是我遇到了与本例相同的问题

现在来看我的问题——在java中,从JNI返回的数组为null。
我做错了什么?任何帮助都将不胜感激。

SetByteArrayRegion()的原型是:

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);


谢谢…它能用。我使用单元素数组进行了测试。我想C还不是我的强项。顺便说一句,我的原始代码中有一个分段错误,不是在这个方法中,而是在GC运行之后,或者在数组再次传递给JNI进行任何操作之后
// 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;