orochi
orochi

Reputation: 1258

How to mantain a JVM pointer in a DllMain call and prevent call JNI_CreateJavaVM twice

I'm loading a DLL and another program call a function I created. This function I made calls some java functions via JNI.

PS: I don't have the control of the DLL method call, it is called my another program.

When I create the JVM I do it with: JNI_CreateJavaVM.

After calling JNI methods I destroy the JVM with: JNI_DestroyJVM().

The problem is that when the function in DLL is called, I create the JVM. But if the JVM is already loaded if fails becasuse of the following problem:


The problem: Re-calling JNI_CreateJavaVM returns -1 after calling DestroyJavaVM

I know I can't call the JNI_CreateJavaVM twice because: JNI_DestroyJVM(), it said "The JDK/JRE still does not support VM unloading, however." Just don't call it, and don't re-initialize it either.


1 - Why The JVM is still loaded in the memory after the DLL_PROCESS_DETACH?

2 - Is there a way to store a global variable in the DllMain? Maybe I could store the (JavaVM *jvm); pointer, and not destroy the jvm after the dll call, so it would be destroyed when the process that call the dll is destroyed.

As I don't have the main program, I just have the DLL call, I can't store a global variable because the DLL_PROCESS_DETACH deletes every variable I created before.

Upvotes: 2

Views: 402

Answers (1)

apangin
apangin

Reputation: 98505

  • Do not call JNI_DestroyJVM if you wish to run Java code more than once during the process lifecycle. Call DetachCurrentThread instead.
  • Before calling JNI_CreateJavaVM make sure JVM is not already created. Use JNI_GetCreatedJavaVMs to get an instance of the loaded JVM, then AttachCurrentThread to get JNIEnv* handle.

Upvotes: 2

Related Questions