简体   繁体   English

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

[英]Getting a null byte array in java from JNI

I am calling a native function from java to return a byte[].我正在从 java 调用本机 function 以返回一个字节 []。
The following is a snippet of the JNI code以下是 JNI 代码片段

jbyteArray result;  
jbyte *resultType;  
result = (*env)->NewByteArray(env, 1);  
*resultType =7;
(*env)->SetByteArrayRegion(env, result, 0, 1, resultType);    
return result;

This is supposed to create a byte array of length 1 and the value 7 is stored in it.这应该创建一个长度为 1 的字节数组,并将值 7 存储在其中。 My actual code is supposed to create an array of dynamic length, but am getting the same problem as in this example.我的实际代码应该创建一个动态长度的数组,但我遇到了与本示例相同的问题。

Now coming to my problem -- in java the array am getting returned from JNI is null.现在来解决我的问题——在 java 中,从 JNI 返回的数组是 null。 What am I doing wrong?我究竟做错了什么? Any help will be appreciated.任何帮助将不胜感激。

The prototype for SetByteArrayRegion() is: SetByteArrayRegion()的原型是:

void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);

The final argument is a memory buffer which SetByteArrayRegion() will copy from into the Java array.最后一个参数是一个 memory 缓冲区, SetByteArrayRegion()将从该缓冲区复制到 Java 数组中。

You never initialize that buffer.您永远不会初始化该缓冲区。 You are doing:你正在做:

jbyte* resultType;
*resultType = 7; 

I'm surprised you don't get a core dump, as you're writing a 7 into some random place in memory.我很惊讶您没有得到核心转储,因为您正在将7写入 memory 的某个随机位置。 Instead, do this:相反,请执行以下操作:

jbyte theValue;
theValue = 7;
(*env)->SetByteArrayRegion(env, result, 0, 1, &theValue);

More generally,更普遍,

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

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM