0

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)?

WHOIF
  • 51
  • 5
  • Read that question that you linked again. Read what the author actually said about his code: "Unfortunately, this code crashes the JVM right after hitting createNewMyStruct(). I'm a bit new to JNI and have no idea what the problem could be." The whole problem with the code in the question is that it **doesn't work**. There is no magic automatic copying like you suggest - the JNI function that should return a jobject is instead returning a pointer to a C structure, and the JVM will crash because you passed bad data to it. – Erwin Bolwidt Mar 08 '18 at 07:25
  • The answer to your question is in this answer to your linked question: https://stackoverflow.com/a/3928915/981744 I'll close this question as a duplicate of your linked question. – Erwin Bolwidt Mar 08 '18 at 07:35

0 Answers0