【发布时间】:2011-07-24 22:38:43
【问题描述】:
目前,我有一个具有以下简化视图的系统。
The entire system run under single process
------------------------------------------
--- DLL0.DLL --- COMMON.DLL (contains global_variable in COMMON.DLL)
EXE ---|
--- DLL1.DLL --- COMMON.DLL (contains global_variable in COMMON.DLL)
COMMON.DLL的源代码如下。
// COMMON.DLL
#ifdef COMMON_EXPORTS
_declspec( dllexport ) int global_variable = 100;
// Function used to access and print global_variable.
__declspec(dllexport) void common_fun_which_access_global_variable();
#else
_declspec(dllimport) int global_variable;
__declspec(dllimport) void common_fun_which_access_global_variable();
#endif
DLL0.DLL的源代码如下。
__declspec(dllexport)
void DLL0() {
printf ("This is DLL0\n");
printf ("In DLL0, global_variable is %i\n", global_variable);
common_fun_which_access_global_variable();
global_variable = 200;
printf ("DLL0 is now setting global_variable to 200\n");
common_fun_which_access_global_variable();
}
DLL1.DLL的源码如下。
__declspec(dllexport)
void DLL1() {
printf ("This is DLL1\n");
printf ("In DLL1, global_variable is %i\n", global_variable);
common_fun_which_access_global_variable();
global_variable = 400;
printf ("DLL1 is now setting global_variable to 400\n");
common_fun_which_access_global_variable();
}
EXE源代码如下。
HINSTANCE instance0 = AfxLoadLibrary(_T("DLL0.dll"));
FARPROC fun0 = GetProcAddress(instance0, "DLL0");
HINSTANCE instance1 = AfxLoadLibrary(_T("DLL1.dll"));
FARPROC fun1 = GetProcAddress(instance1, "DLL1");
_fun0();
_fun1();
输出如下。
This is DLL0
In DLL0, global_variable is 100
In COMMON, global_varialbe is 100
DLL0 is now setting global_variable to 200
In COMMON, global_varialbe is 200
This is DLL1
In DLL1, global_variable is 200 <-- I wish 100 is being printed.
In COMMON, global_varialbe is 200 <-- I wish 100 is being printed here too.
<-- I wish DLL0 and DLL1 have their own instance of
<-- global_variable respectively.
DLL1 is now setting global_variable to 400
In COMMON, global_varialbe is 400
整个系统在单个进程中执行。尽管DLL0.DLL 和DLL1.DLL 都被显式加载,但依赖关系COMMON.DLL 在整个应用程序生命周期中只会被加载一次。 EXE 不会加载相同的COMMON.DLL 两次。
有什么办法,我可以在不违反任何一条规则的情况下实现以下目标?
- DLL0 和 DLL1 可以有自己的
global_variable实例? -
global_variable必须是全局的,并且重新在COMMON.DLL内部? -
COMMON.DLL将通过使用 LIB 文件的隐式链接加载。 - 不能将
COMMON.DLL重命名为COMMON-DLL0.DLL和COMMON-DLL1.DLL。 - 没有静态链接。
- 如果 DLL0 更改了
global_variable的值,从 DLL0 调用common_fun_which_access_global_variable应该可以访问 DLL0 的更改值。但是,从 DLL1 调用common_fun_which_access_global_variable应该不会实现这些更改。
** 我知道这太过分了。但我现在正在处理遗留代码。你知道:)
并排组装能够解决此类问题吗?我的理解是,并行程序集用于解决多个同名但版本不同的 DLL 问题。我不确定它是否适用于我的上述情况?
或者,我应该反过来问吗?我们如何在同一个 EXE 中加载 2 个 COMMON.DLL 实例?
【问题讨论】:
-
对,太多了。你不能让这个工作。放弃第 4 条
标签: c++ windows visual-c++ dll