Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared memory in DLLs

Tags:

c++

c

windows

dll

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?

like image 398
user986654 Avatar asked Oct 09 '11 18:10

user986654


1 Answers

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.

like image 164
selbie Avatar answered Sep 19 '22 04:09

selbie