我有一个主程序和一个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的正确方法吗?
答案 0 :(得分:2)
有一个专门用于此目的的功能:FreeLibraryAndExitThread
。