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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With