动态链接 DLL 需要与其调用者共享全局变量
我有一个静态库 libStatic ,它定义了一个全局变量,如下所示
头文件 libStatic/globals.h
:
extern int globvar;
代码文件 libStatic/globals.cpp
:
int globvar = 42;
DLL libDynamic 和可执行文件 runner 正在使用此全局变量。此外,libDynamic
在运行时链接到 runner(通过 LoadLibrary()
、GetProcAddress()
和工作...)
我知道这将导致 globvar
被创建两次,一次在 runner 堆中,一次在 libDynamic 堆中>,这当然是非常不可取的。
这附近有什么好的办法吗?如何确保 libDynamic 和 runner 使用相同的 globvar
?
I have a static library libStatic that defines a global variable like this
Header file libStatic/globals.h
:
extern int globvar;
Code file libStatic/globals.cpp
:
int globvar = 42;
The DLL libDynamic and the executable runner are using this global variable. Furtheron, libDynamic
is linked at run-time into runner (via LoadLibrary()
, GetProcAddress()
, and the works...)
I understand this will lead to globvar
being created twice, once in the heap of runner and once in the heap of libDynamic, which is of course very undesirable.
Is there a good away around this? How can I ensure that libDynamic and runner are using the same globvar
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个简单的方法是让
.DLL
指向可执行文件的全局变量。加载后,您将立即调用该库中的一个特殊函数(例如SetGlobVar(int*)
)。这样,库将始终指向与.EXE
相同的全局变量。An easy way would be to let the
.DLL
point to the global variable of the executable. Right after loading you would call a special function inside that library (something likeSetGlobVar(int*)
). That way the library will always point to the same global variable as the.EXE
.