Process-wide global

Started by
1 comment, last by antareus 19 years, 7 months ago
I am continuing a much older discussion. Motivation: I need to store some global data for a Win32 app framework. There can only be one copy of this global data throughout an entire application. There may be DLLs loaded with their own separate heaps, and I'd like to cleverly redirect their calls to the one 'true' instance. I would like to do this all without delegating the data storage to a dedicated DLL. Construction: I envision users making some sort of Application object in WinMain, thus christening that thread as the main thread of execution, and that module as the executing module. Now I'd like code in other modules to 'magically' find that single instance of data when they need to use it. I'd use a Meyers Singleton to do the lookup and cache the result (read on): The best idea I've had so far is to use SetEnvironmentVariable() and store a text representation of the pointer in there. Unfortunately you cannot just stuff any number in there as SetEnvironmentVariable() dereferences it to copy the string out. So I could turn the address into a string, store it in there, and then turn it back into an address anytime someone needs to access the one and only instance. Seems really hacky. Another good suggestion is to use the registry but that would be even more code. All I really want is to change four bytes such that I can get to this information wherever I am in the process. Thread local storage seems like an ideal solution, except we arrive back at the same problem: how do we determine what index to use for TLS? TlsAlloc() may not always return the same index! Nor can the atom functions be used; they only let you store a key instead of letting you associate a value with it. One idea that may work is to exploit the fact that the HMODULE for the executable is actually a pointer to the exe mapped onto memory. Now this is getting dangerous....:)
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
Advertisement
What about the Win32 API functions CreateFileMapping/OpenFileMapping?
I figured out a workable solution.

The executable module hosting the framework exports a single function to return a pointer to the process-wide global. If it isn't found in the main loaded module, all modules of the process can be enumerated and a search made. After the proper module is found, the result is cached and used in subsequent operations.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis

This topic is closed to new replies.

Advertisement