动态链接 DLL 需要与其调用者共享全局变量

发布于 2024-09-01 15:06:07 字数 620 浏览 6 评论 0原文

我有一个静态库 libStatic ,它定义了一个全局变量,如下所示

头文件 libStatic/globals.h

extern int globvar;

代码文件 libStatic/globals.cpp

int globvar = 42;

DLL libDynamic 和可执行文件 runner 正在使用此全局变量。此外,libDynamic 在运行时链接到 runner(通过 LoadLibrary()GetProcAddress() 和工作...)

我知道这将导致 globvar 被创建两次,一次在 runner 堆中,一次在 libDynamic 堆中>,这当然是非常不可取的。

这附近有什么好的办法吗?如何确保 libDynamicrunner 使用相同的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2024-09-08 15:06:07

一个简单的方法是让 .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 like SetGlobVar(int*)). That way the library will always point to the same global variable as the .EXE.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文