I need get byte array from jni to Java. Ex: I have a byte array byte[] a = {1,2,3,4,5,6}
JNIEXPORT jbyteArray JNICALL Java_com_vn_getArray (JNIEnv *env, jobject obj) {
jbyte[] a = {1,2,3,4,5,6};
return a;
}
I do not know how to return a byte array from jni.
Can someone help me? Please!
In Java, an array is an object. So to hand a byte array from C or C++ over to java you will need to instantiate a jbyteArray, and return that. Instead of a C array. To solve that, see the following code:
JNIEXPORT jbyteArray JNICALL Java_Test_returnArray
(JNIEnv *env, jobject This)
{
jbyte a[] = {1,2,3,4,5,6};
jbyteArray ret = env->NewByteArray(6);
env->SetByteArrayRegion (ret, 0, 6, a);
return ret;
}
Based on this link
I do like that and it's working
JNIEXPORT jbyteArray JNICALL Java_com_vn_getArray(JNIEnv *env, jobject obj) {
jbyte byteUrl[] = {1,2,3,3,4};
int sizeByteUrl = 5;
jbyteArray data = (*env)->NewByteArray(env, sizeByteUrl);
if (data == NULL) {
return NULL; // out of memory error thrown
}
// creat bytes from byteUrl
jbyte *bytes = (*env)->GetByteArrayElements(env, data, 0);
int i;
for (i = 0; i < sizeByteUrl; i++) {
bytes[i] = byteUrl[i];
}
// move from the temp structure to the java structure
(*env)->SetByteArrayRegion(env, data, 0, sizeByteUrl, bytes);
return data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With