我有一个主程序和一个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的正确方法吗?
完全有一个功能:FreeLibraryAndExitThread
。