Getting array of null bytes in java from JNI

I call the native function from java to return the byte [].
Below is a JNI code snippet

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

It is supposed to create a byte array of length 1 and store the value 7 in it. My actual code should create an array of dynamic length, but I get the same problem as in this example.

Now the transition to my problem - in java, the array retrieved from the JNI is null. What am I doing wrong? Any help would be appreciated.

+5
source share
1 answer

The prototype for SetByteArrayRegion()is:

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

The final argument is the memory buffer that SetByteArrayRegion()will be copied from the Java array.

You never initialize this buffer. You do:

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

All Articles