Reputation: 109
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'
Upvotes: 1
Views: 3664
Reputation: 98505
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.
Upvotes: 3
Reputation: 2486
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
Upvotes: 0