Can I allocate a memory block in one JNI function, and release one in another JNI function?
I'm afraid, that jvm catchs call of malloc from native function, and release it when function finished; For example, is this code correct:
char * buffer;
JNIEXPORT jlong JNICALL Java_test_init(JNIEnv *env, jobject obj) {
buffer = malloc(1000);
return (jlong)buffer; //for check it
}
JNIEXPORT void JNICALL Java_test_use(JNIEnv *env, jobject obj) {
// some code, that used buffer
}
JNIEXPORT void JNICALL Java_test_done(JNIEnv *env, jobject obj) {
free(buffer);
}
UPD: I read about direct buffer (NewDirectByteBuffer) and global refererences (NewGlobalRef) but i asked, can I allocate memory without use JNI API, just with call 'malloc'
If you have a global reference for your object, then it stays valid after returning from your JNI function. Which means that your example is correct. For further information look here: local and global references
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.