Download demo project - 37 Kb
Introduction
This is a very simple how to for setting up a shared data segment in a DLL.
A shared data segment is used when you want to share variable values among
several exe's.
This is not as clever as a semaphore and not as powerful as a COM
Event_Sink_MAP
. However, it has very little overhead and it is very simple
to implement. It is worth while knowing things can be done this easy.
A little background.
One advantage of using a DLL is that several processes (exe's) can share a
code segment. They share the code segment but each process gets it's own
data segment. Therefore if five processes use a DLL there is only one code
segment and five data segments.
What is a shared data segment?
A data segment is a chunk of main memory that holds the programs variables.
It is the thing that gets swapped to the swap file.
A shared data segment in a DLL is simply one or more variables that are not
unique to a specific process. In many respects this example code is very
similar to a semaphore. If you really think that more than one process at a
time is going to be updating the shared variables, then maybe a semaphore is
the right choice for you. However we will control the update of the shared
variables via critical sections, therefore this technique is just as safe as
a true semaphore. What has more overhead, the ramp up cost of using
CSemaphore
all the time or the infrequent spin locking this approach might
incur? The answer depends of what you are doing.
What makes a data segment shared?
These three pragma statements override the default data segment behavior and
creates a shared data segment. See MyClass.cpp in the DLL.
...
#pragma data_seg("SHARED")
#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
Summary
That's it. The download zip is mostly window dressing. The code does
demonstrate how to use a
PostMessage
as a simple alternative to COM's message
sink. Furthermore, the code shows how to set up a critical section which is
something you may or may not want. Depending on if you intend to allow
multiple processes to update the shared data segment or just read it.
The code is written in VC 5. First build the DLL TestMemorySpace and then
the driver executable Testexe.exe. Start two instances of the test exe, keep them
both maximized, and click the button that says 'Read Me First'.
In this simple 'How To' I use two instances of the same exe, you could use X
number of different exe's that all share this DLL.
If you learn something from this code - great! If you can improve upon it, I
would love to learn from you. I maintain no rights of any kind to it. This
code was not plagiarized from any other source.
Good Luck and trust me the code is simpler than the explanation.