Dynamic-linked DLL needs to share a global variable with its caller
I have a static library libStatic that defines a global variable like this
Header file libS开发者_运维技巧tatic/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
?
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
.
精彩评论