应该在程序结束时调用 FreeLibrary 吗?

Should FreeLibrary be called at the end of the program?

我没有在文档中找到这个:如果我需要一个 DLL 处理程序直到程​​序结束,我是否仍然应该在我的调用程序结束之前调用 FreeLibrary,还是不需要?

最佳做法是始终 为任何相应的LoadLibrary 调用调用FreeLibrary。但是,跳过该调用并仅结束您的程序可能不会导致任何严重问题,因为终止调用过程似乎与减少 DLL 的 'reference count' 具有相同的效果(因为调用 FreeLibrary 将做)。

来自 Microsoft documentation(加粗我的):

The reference count is decremented each time the FreeLibrary or FreeLibraryAndExitThread function is called for the module. When a module's reference count reaches zero or the process terminates, the system unloads the module from the address space of the process. Before unloading a library module, the system enables the module to detach from the process by calling the module's DllMain function, if it has one, with the DLL_PROCESS_DETACH value. Doing so gives the library module an opportunity to clean up resources allocated on behalf of the current process. After the entry-point function returns, the library module is removed from the address space of the current process.

为什么最好显式调用FreeLibrary()的一个原因是你可以处理调用returns的情况if/when失败(即零)状态。有关 DLL 无法正确卸载的具体方式或原因的详细信息超出了本答案的范围,但您可能会发现此讨论很有帮助:What to do when FreeLibrary API call fails?

另一个原因是您的代码的任何未来开发人员可能没有意识到您正在使用程序终止来隐式 卸载 DLL,并且在某些情况下,这可能会导致问题再往前走。