如何在加载DLL时加载JVM并在卸载DLL时释放它

时间:2011-11-19 11:26:26

标签: java windows dll jvm java-native-interface

我正在开发一个dll,它通过JNI调用jar来完成大部分工作。如何创建DLL,使其在加载DLL时只创建一次JVM,并在卸载DLL时释放它?

1 个答案:

答案 0 :(得分:1)

提供DllMain功能,在此之后构图:

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;
}