加载DLL不初始化静态C ++类 [英] Loading DLL not initializing static C++ classes
问题描述
我有一个在运行时加载的DLL。该DLL依赖于一个静态变量用于内部工作(它是一个std :: map),这个变量在DLL中定义。
I have a DLL that is being loaded at run-time. The DLL relies on a static variable for internal workings (it is a std::map), this variable is defined within the DLL.
当我调用第一个函数DLL加载后,我从DLL中得到一个SegFault,映射从未初始化。从我从DLL载入中读取的一切,静态和全局数据初始化应该发生在甚至调用DLLMain之前。
When I call the first function from the DLL after loading, I get a SegFault from the DLL, the map was never initialized. From everything I have read from DLL Loading, static and global data initialization should happen before even the call to DLLMain.
为了测试静态初始化,我添加了一个静态结构打印出来
To test static initialization I added a static struct that prints out a message, and even threw in a breakpoint for good measure.
static struct a
{
a(void) { puts("Constructing\n"); }
}statica;
没有消息,或在DLLMain或函数调用之前断开。
There was no message, or break before DLLMain or the function is called.
这是我的加载代码:
dll = LoadLibrary("NetSim");
//Error Handling
ChangeReliability = reinterpret_cast<NetSim::ChangeReliability>
(GetProcAddress(dll, "ChangeReliability"));
ChangeReliability(100);
我已经验证了dll版本是正确的,重建整个项目多次,区别。
I have verified that the dll version is the correct one, rebuilt the entire project multiple times, but no difference. I am fresh out of ideas.
推荐答案
链接DLL时,是否指定了ENTRY开关?如果是这样,它将覆盖链接器的默认值,即DllMainCRTStartup。因此,不会调用_CRT_INIT,反过来,将不会调用全局初始化器,这将导致未初始化的全局(静态)数据。
When you linked your DLL, was the /ENTRY switch specified? If so, it'll override the linker's default which is DllMainCRTStartup. As a result, _CRT_INIT won't be called and, in turn, the global initializers won't be called which will result in uninitialized global (static) data.
如果你要为自己的入口点指定/ ENTRY,在进程附加和进程分离期间需要调用_CRT_INIT。
If you are specifying /ENTRY for your own entry point, you need to call _CRT_INIT during process attach and process detach.
如果不指定/ ENTRY,使用CRT的进入点,调用_CRT_INIT在进程连接/分离后调用你的DllMain。
If you are not specifying /ENTRY, the linker should be using the CRT's entry point which calls _CRT_INIT on process attach/detach before calling into your DllMain.
这篇关于加载DLL不初始化静态C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!