I am trying to pass a byte array (with random data) from native to Java and I am not sure if this causes any memory leak or not. Here's the C++ code.
JNIEXPORT jbyteArray JNICALL Java_com_sample_test_jni_TestJNI_return_1byte_1array
(JNIEnv *env, jobject obj) {
unsigned char *byteArray = new unsigned char[LENGTH];
srand(12345);
for(int i = 0;i < LENGTH;i++) {
byteArray[i] = rand() % 64;
}
jbyteArray data = (env)->NewByteArray(LENGTH);
env->SetByteArrayRegion(data, 0, LENGTH, (jbyte*)byteArray);
delete(byteArray);
return data;
}
And here's the Java code.
class TestJNI {
static {
System.loadLibrary("foobar");
}
public native byte[] return_byte_array();
public static void main(String[] args) {
byte[] data = new TestJNI().return_byte_array();
System.out.println("Data length " + data.length);
}
}
My doubt is whether the jbytearray allocated in native code will be garbage-collected by Java. I cannot free it in native side.
Also, are there good docs which describe JNI memory management with examples?