为什么不从入口点函数调用FreeLibrary? [英] Why not call FreeLibrary from entry point function?

查看:213
本文介绍了为什么不从入口点函数调用FreeLibrary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要动态多次调用DLL的DLL。我想保留被调用者加载,然后卸载它,当我的DLL卸载。但根据微软,这是一个坏主意


入门点函数只应该
执行简单的初始化任务
,不应该调用任何其他DLL
加载或终止函数。对于
示例,在入口点函数中,
不应直接或间接地
调用LoadLibrary函数或
LoadLibraryEx函数。另外,
当进程
终止时,您不应该调用FreeLibrary
函数。


这是违规代码。有人可以解释为什么我不能从我的DLL的入口点调用LoadLibrary和FreeLibrary?

  BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved

{
switch(ul_reason_for_call){
case DLL_PROCESS_DETACH:
if(hLogLib!= NULL)FreeLibrary (hLogLib);
break;
}
return TRUE;
}


解决方案

我想我已经找到答案


入门点函数应该
只执行简单的初始化或
终止任务。它不能调用
LoadLibrary或LoadLibraryEx
函数(或调用
这些函数的函数),因为这可能
在DLL
加载顺序中创建依赖循环。这可能导致在系统
执行其初始化代码之前使用DLL

类似地,入门点函数
不能在进程终止期间调用Freebibrary函数
(或调用FreeLibrary的函数)
,因为
这可能导致在系统执行
终止代码之后,使用
的DLL。



I'm writing a DLL that needs to call a separate DLL dynamically multiple times. I would like to keep the callee loaded and then just unload it when my DLL is unloaded. But according to Microsoft, that's a bad idea.

The entry point function should only perform simple initialization tasks and should not call any other DLL loading or termination functions. For example, in the entry point function, you should not directly or indirectly call the LoadLibrary function or the LoadLibraryEx function. Additionally, you should not call the FreeLibrary function when the process is terminating.

Here's the offending code. Can somebody explain why I shouldn't call LoadLibrary and FreeLibrary from my DLL's entry point?

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
                     )
{
switch (ul_reason_for_call) {
    case DLL_PROCESS_DETACH :
            if (hLogLib != NULL) FreeLibrary(hLogLib);
            break;
    }
    return TRUE;
}

解决方案

I think I've found the answer.

The entry-point function should perform only simple initialization or termination tasks. It must not call the LoadLibrary or LoadLibraryEx function (or a function that calls these functions), because this may create dependency loops in the DLL load order. This can result in a DLL being used before the system has executed its initialization code. Similarly, the entry-point function must not call the FreeLibrary function (or a function that calls FreeLibrary) during process termination, because this can result in a DLL being used after the system has executed its termination code.

这篇关于为什么不从入口点函数调用FreeLibrary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆