I have a requirement where two separate applications need to access and modify an object contained in a DLL (all control logic for the application is written in C and operates from a DLL). A UI exe (with minimal logic, written in C ) consumes this DLL and interacts with the main control logic DLL. I am looking to add an additional exe (written in C#) to run multiple web based services that would also need to access the same object contained in the DLL.
CodePudding user response:
Yes it's called Shared Memory. The dll needs to call CreateFileMapping to allocate the region of memory to be shared. Then call MapViewOfFile to well.. map the file into memory. Then multiple processes can access this mapped memory through its name.
CodePudding user response:
This is not a question about c per se but about how your operating system deals with shared libraries. From my experience in looking at the application loader behavior on Solaris systems, the answer is no. I presume the behavior of Solaris is followed by Windows, Linux, etc. but I suppose there could be an exotic operating system that does just want you ask for (I'm looking at you QNX).
Basically if you create a global variable, let's say:
int foo = 5;
and compile your dll and analyze the content of your dll, you would see foo included in some read/write data section.
Since the section is read/write, when the exe starts and loads the dll, the operating system would create a copy of that section for the exe. Now your exe can change the value to any int it wants, but it only changes its copy of foo.
If you start up another exe, it too will load the dll and it too will get a copy of the section. That exe will have it's own copy of foo and it will initially be set to 5.
Read only sections behave differently so if you were to define foo as follows:
static const int foo = 5;
It would end up in a read only section of the dll and every exe would refer to the same foo in memory. It doesn't allow you to do what you're trying to do but it is nice thing to know as it saves memory. A good rule of thumb is to make everything static
and const
when possible.