What is the scope of global variables inside C++ DLLs
Let's say a 3rd-party DLL X has a global variable G
I write two separate DLLs (as plugins for an app) P1 & P2 which both dynamically load X.
The application's process loads my two plugins P1 & P2 so both are loaded at the same time.
Does this mean I have one instance of G or two?
edit:
The usage scenario is X is a 3D rendering engine which has 开发者_StackOverflow中文版singletons wrapping system resources, it is simply not designed to expect multiple instances in a process - you can run 2 X-based apps at once but trying to initialize X twice in the same app will mess up. The plugins are both using X but would be deployed as separate installers, they would not know about each other and would not share the same X.dll file - typicall each plugin would have its own dir for storing required resources and DLLs.
The DLL loading routines exposed in the Win32 API make sure you only have one copy of a DLL loaded per process (see the "Remarks" section here, particular paragraph three and the last paragraph before the Security Remarks section, where per-process reference counts are discussed). I assume you're just calling LoadLibrary
or similar, in which case you have one instance of G.
It appears as thought it is possible to circumvent this by having multiple copies of the DLL in question in different locations (as noted in this sort-of related question), and loading each of those, in which case you could end up with multiple copies of all of the data in each DLL (G included).
The answer is that there is a single instance of global variable in each process. It's all explained at MSDN: Dynamic-Link Library Data
精彩评论