How does sharing memory works in DLLs?
When DLL is attached to process, it uses the same memory addresses as process. Let's assume we have following function in DLL:
int * data = 0;
int foo()
{
if (!data) data = new int(random());
return *data;
}
When process A calls this function it creates new object (int) and returns its value.
But now process B attaches this DLL. It calls foo() but I don't understand how would it work, because data
is in process' A memory space. How would B be able to directly use it?
You are correct, DLLs do NOT share memory across processes by default. In your example, both process A and B would get a separate instance of "data".
If you have a design where you want to have global variables within a DLL shared across all the processes that use that DLL, you can use a shared data segment as described here. You can share pre-declared arrays and value types through shared data segments, but you definitely can't share pointers.
You are mistaking two different concepts here - dlls are sharing memory in this sense, that everything that is not (ever) going to change is shared (physically). It is saving your RAM cause lot's of data in DLL is code and other constant data, so system uses only one copy of it, no matter how many processes use it. This is important on system level - from application point of view there is no sharing visible at all.
However internal data like the one described here is not shared among processes - every process gets its own copy. If you are interested in sharing memory between processes, you need other mechanisms. You might be interested in Creating Named Shared Memory.
Process B will have its own separate memory space that has nothing to do with Process A. The data
variable will be created inside the process space of B.