I have a byte[] in Java which reports its length as 256 bytes which I pass to a native function in C.
When I tried to get the data out of this array it was completely wrong and when I printed it out it did not match the data I printed out right before I passed it to C.
I tried a few ways to access the data including both GetByteArrayRegion and GetByteArrayElements but nothing seems to give me the data I expect.
As I was investigating this I tried to look at what JNI believed the jbyteArray‘s length was with GetArrayLength – it reported the length as 1079142960, far more than the 256 bytes I expected. Also the value was different each time the function was called, for example another time GetArrayLength returned 1079145720.
Here is the code I am using to access the array:
JNIEXPORT jbyteArray function(JNIEnv* env, jbyteArray array) {
int length = (*env)->GetArrayLength(env, array);
jbyte data[256];
(*env)->GetByteArrayRegion(env, array, 0, 256, data);
//also tried
//jbyte *data = (jbyte*) (*env)->GetByteArrayElements(env, array, NULL);
}
This seems pretty straight forward so I’m not really sure what is going on. The array seems fine from Java but it was generated in C and passed back so I suppose something might have gone wrong there that Java doesn’t care about but breaks the array when it comes back to C.
Here is the code I used to generate the array and pass it back to Java:
//there is some openSSL stuff here that sets up a pointer to an RSA struct called keys that is size bytes large
jbyteArray result = (*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, result, 0, size, (jbyte*)keys;
Am I missing something?
Thanks
This function prototype is incorrect:
The second argument is either a
jclassor ajobject. If your method is static, it should be:And if it’s not static:
You are treating the class or object as an array, which explains the unexpected results that you get.