简体   繁体   中英

Shared memory in DLLs

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 .

进程B将拥有自己独立的内存空间,与进程A无关。 data变量将在B的进程空间内创建。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM