如何根据DLL端的请求卸载DLL模块以卸载它?

问题描述 投票:1回答:1

我有一个主程序和一个DLL库。两个代码可以总结如下。

// DLL Module (Start)
class DllModuleClass : public IDllModuleInterFace
{
    public:
        // ...
        void Terminate() override
        {
            // ...
            pMainModuleObject->OnDllModuleObjectTerminated();   // Notify the main program that the DLL can be unloaded now.
            // Error occurs at this point (as soon as OnDllModuleObjectTerminated() returns), because it frees the DLL module and this region does not exist anymore.
        }
        // ...
    private:
        IMainModuleInterFace * pMainModuleObject;
}

IDllModuleInterFace * GetDllModuleClassInstance();
// DLL Module (End)

// Main Module (Start)
class MainModuleClass : public IMainModuleInterFace
{
    public:
        // ...
        void OnDllModuleObjectTerminated() override
        {
            FreeLibrary(hDllModule); // DLL module is freed from memory here.
        }   // Tries to go back to `Terminate()` inside the DLL module, but the DLL module is freed now.
        // ...
    private:
        IDllModuleInterFace * pDllModuleObject;
}
// Main Module (End)

在我的代码中,DLL模块调用主模块中的函数,以通知主模块可以卸载DLL。主模块这样做,从内存中卸载DLL。但DLL的调用者尚未返回。因此,在卸载DLL之后,DLL中仍然存在一个仍在运行的函数。这会导致明显且不可避免的运行时错误。

你能建议一种在这个结构中卸载DLL的正确方法吗?

c++ winapi design-patterns dll
1个回答
2
投票

完全有一个功能:FreeLibraryAndExitThread

© www.soinside.com 2019 - 2024. All rights reserved.