All codes are referenced from this question.
C header file:
typedef struct _MyStruct {
float member;
} MyStruct;
MyStruct* createNewMyStruct();
JNI wrapper in C:
JNIEXPORT jobject JNICALL
Java_com_myorg_MyJavaClass_createNewMyStruct(JNIEnv *env, jobject this) {
return createNewMyStruct();
}
Java code that uses JNI to call C code above:
public class MyJavaClass {
static { System.loadLibrary("MyJniLibrary"); }
private native MyStruct createNewMyStruct();
private class MyStruct {
float member;
}
public void test() {
MyStruct foo = createNewMyStruct();
}
}
When executing test() method, createNewMyStruct() will be called. The C code will ask for space from OS (perhaps using malloc()), to create one instance of MyStruct. I believe this part of memory is not in JVM heap.
But when createNewMyStruct() returns, will JAVA copy this part of memory into its JVM heap? In other words, after the execution of
MyStruct foo = createNewMyStruct();
, does "foo" (as a variable in stack) point to the origin memory that is allocated in the C code (so that C and JAVA have shared memory), or to some place in the JVM heap (a duplica of MyStruct)?
Furthermore, if it is the former case, then will that shared memory participate in Java GC? Because if so, then if I also have some memory management module in the C code, wouldn't that shared memory possibily be deallocated twice (by Java GC and C code respectively)?