首页 > 解决方案 > 如何根据 DLL 端的请求卸载 DLL 模块以卸载它?

问题描述

我有一个主程序和一个 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++winapidesign-patternsdll

解决方案


有一个功能正是为此目的:FreeLibraryAndExitThread.


推荐阅读