简体   繁体   中英

memory allocated in native code between jni calls

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'

Yes, this is a valid approach.

JVM has no control on what native code does; it would possibly break many third-party libraries if it tried to intercept malloc/free calls. Futhermore, the similar approach is used by JDK code itself. Examples: 1 , 2 , 3 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM