JNI Environment pointer in a static c++ object and calling a java function taking a string argument twice in a row crashes the JVM

前端 未结 1 658
刺人心
刺人心 2020-12-07 04:30

So on my commentators request I have finally found an MCVE that reproduces my error. So the general setup is that Java uses JNI to call into a dll, and the dll grabs hold of

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 05:20

    There are several mistakes in your code.

    1. jobject myObject and jclass myClass are reused across JNI calls.

      All jobjects created inside a JNI method are local references by default. Whenever a JNI method returns, all local references are automatically released.

      If you want to reuse jobject (or jclass which is also an object reference) across method calls, you should convert it to a global reference using NewGlobalRef. When a global reference is no longer needed, it should be deleted by DeleteGlobalRef, otherwise referenced object will never be garbage-collected.

    2. JNIEnv* is cached.

      In general, JNIEnv* should never be stored for later reuse. Instead you should use JNIEnv* provided as the first argument to each JNI function. Alternatively it may be obtained by GetEnv call. Note that each thread has its own JNIEnv* which is not applicable to other threads.

    0 讨论(0)
提交回复
热议问题