I\'d like to share a static/global variable only between a process and a dll that is invoked by the process. The exe and dll are in the same memory address space. I don\'t w
I found this to be such an interesting question that I took the time to write an extensive tutorial on how to use DLL's to share data among multiple DLLs (either implicitly, or explicitly linked) but also make sure the data is not shared among separate processes of the same executable file.
You can find the full article here: http://3dgep.com/?p=1759
A solution to this problem that I found to work quite well is to create a "common" or "shared" dll that defines all the data and methods that you want to share across multiple DLL's (but not shared among processes).
Let's suppose you want to define a singleton class that can be accessed from the main application code (the EXE) but you also want to access the singleton instance in shared (either implicitly or explicitly linked DLL). First, you would need to declare the singleton class in the "common" DLL:
// Export the class when compiling the DLL,
// otherwise import the class when using the DLL.
class __declspec(dllexport) MySingleton
{
public:
static MySingleton& Instance();
};
When compiling the CommonDLL project, you have to export the class declaratoin by decorating the class with __declspec(dllexport)
and when you are using the DLL (in the application for example), the class definition needs to be imported by decorating the class with __declspec(dllimport)
.
When exporting a class by decorating the class with the __declspec(dllexport)
specifier, all of the class's methods and data (even private data) are exported from the DLL and usable by any DLL or EXE that implicitly links to the common DLL.
The definition of the MySingleton class might look something like this:
MySingleton& MySingleton::Instance()
{
static MySingleton instance;
return instance;
}
When compiling the common dll, two files will be produced:
If you link you application against the exported LIB file, then the DLL file will be implicitly linked at runtime (as long as the DLL file is found in the DLL search paths) and you will have access to the singleton defined in the CommonDLL.DLL file.
Also, any shared library (plug-ins for example) that also links against the CommonDLL.LIB file will have access to the same singleton instances when dynamically loaded by the application.
For a full explanation of this solution including a source code sample, check-out the following article I posted titled "Using Dynamic Link Libraries (DLL) to Create Plug-Ins":
http://3dgep.com/?p=1759