DLL 中全局变量的使用限制(适用于 Windows)
首先,我知道全局变量是邪恶的:)但是,有合法的情况为什么我需要使用它。
我知道 DllMain 中可以执行的内容有非常严格的限制(没有 LoadLibraries、没有 COM 初始化等)。
我知道全局变量是在 DllMain DLL_PROCESS_ATTACH 之前初始化的。
全局变量初始化时是否有相同的限制?
我找到了微软文章: http://msdn.microsoft.com/en-us/library /988ye33t 但是,它没有任何与限制相关的详细信息。
我还看到了另一个 Stackoverflow 问题:在中声明的全局变量会发生什么DLL? 以下是其中的片段:“在 DllMain 中禁止执行某些操作。在构造函数中,这些操作也可能被禁止。”
然而,评论者似乎不确定这种限制是否真的存在。
如果有任何有关此主题的信息,我将不胜感激。
First of all, I know global variables are evil :) However, there is legit case why I need to use one.
I know that there are very strict limitation on what can be executed in DllMain (no LoadLibraries, no COM initialization and so on).
And I know that global variables are initialized just prior DllMain DLL_PROCESS_ATTACH.
Do I have the same limitation while global variable initialization?
I found Microsoft article: http://msdn.microsoft.com/en-us/library/988ye33t
However, it doesn't have any details related to the limitations.
I saw also another Stackoverflow questions: What happens to global variables declared in a DLL?
Here is snippet from there "There are things that are forbidden to do in the DllMain. Those things are probably forbidden, too, in the constructors."
However, it looks like commentor isn't sure whether such limitations are really exist.
I would appreciate any information on this subject.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我的这个答案中所解释的,真正的dll入口点(即真正的 DllMain)由 CRT 获取,在 DLL_PROCESS_ATTACH 上初始化其内容,调用全局变量的构造函数,然后调用“假”
>DllMain
(即您作为程序员所看到的DllMain
)。MSDN 文档将
DllMain
称为真实 dll 入口点,因此所有限制也适用于全局对象的构造函数,因为它们是由它调用的。这是避免全局变量的另一个原因:它们的构造函数中的代码是从
DllMain
调用的,但这并不明显,因此如果在DllMain< 中执行“禁止”的操作时出现问题, /code> 可能需要很长时间才能确认有问题的代码位于此类构造函数中。
As explained in this answer of mine, the real dll entrypoint (i.e. the real
DllMain
) is taken by the CRT, that, onDLL_PROCESS_ATTACH
, initializes its stuff, calls the constructors of the globals and then call the "fake"DllMain
(i.e. what you as a programmer see asDllMain
).The MSDN documentation calls
DllMain
the real dll entrypoint, so all the restrictions apply also to the constructors of global objects, since they are called by it.This is yet another reason to avoid globals: the code in their constructors is called from
DllMain
, but this is not evident, so in case of problems coming from doing "forbidden" things inDllMain
it may take a lot of time before acknowledging that the offending code is in such constructors.