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

jog*_*ito 5 java java-native-interface

我从java调用一个本机函数返回一个byte [].
以下是JNI代码的片段

jbyteArray result;  
jbyte *resultType;  
result = (*env)->NewByteArray(env, 1);  
*resultType =7;
(*env)->SetByteArrayRegion(env, result, 0, 1, resultType);    
return result;
Run Code Online (Sandbox Code Playgroud)

这应该创建一个长度为1的字节数组,并将值7存储在其中.我的实际代码应该创建一个动态长度的数组,但是我遇到了与此示例中相同的问题.

现在来解决我的问题 - 在java中,从JNI返回的数组为null.我究竟做错了什么?任何帮助将不胜感激.

Qua*_*nic 7

原型SetByteArrayRegion()是:

void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
Run Code Online (Sandbox Code Playgroud)

最后一个参数是一个内存缓冲区,SetByteArrayRegion()它将复制到Java数组中.

你永远不会初始化那个缓冲区.你在做:

jbyte* resultType;
*resultType = 7; 
Run Code Online (Sandbox Code Playgroud)

我很惊讶你没有得到核心转储,因为你7在内存中写了一个随机的地方.相反,这样做:

jbyte theValue;
theValue = 7;
(*env)->SetByteArrayRegion(env, result, 0, 1, &theValue);
Run Code Online (Sandbox Code Playgroud)

更普遍,

// 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);
Run Code Online (Sandbox Code Playgroud)

要么

// 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;
Run Code Online (Sandbox Code Playgroud)