shawn
shawn

Reputation: 4223

How do I load a JVM when a DLL is loaded and free it when the DLL is unloaded

I'm developing a dll which invokes a jar to do most of the work through JNI. How can I create the DLL such that it creates the JVM only one time when the DLL is loaded and frees it when the DLL is unloaded?

Upvotes: 0

Views: 278

Answers (1)

mah
mah

Reputation: 39807

Provide a DllMain function, patterned after this:

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL,  // handle to DLL module
    DWORD fdwReason,     // reason for calling function
    LPVOID lpReserved)     // reserved
{
    // Perform actions based on the reason for calling.
    switch(fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // Initialize once for each new process.
            // Return FALSE to fail DLL load.
            LOAD_JVM(); // <-----------------------------------------
            break;
        case DLL_THREAD_ATTACH:
            // Do thread-specific initialization.
            break;
        case DLL_THREAD_DETACH:
            // Do thread-specific cleanup.
            break;
        case DLL_PROCESS_DETACH:
            // Perform any necessary cleanup.
            UNLOAD_JVM(); // <-----------------------------------------
            break;
    }
    // Successful DLL_PROCESS_ATTACH.
    return TRUE;
}

Upvotes: 1

Related Questions