windows DLL 中的共享内存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7705724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shared memory in DLLs
提问by user986654
How does sharing memory works in DLLs?
在 DLL 中共享内存是如何工作的?
When DLL is attached to process, it uses the same memory addresses as process. Let's assume we have following function in DLL:
当 DLL 附加到进程时,它使用与进程相同的内存地址。假设我们在 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?
当进程 A 调用此函数时,它会创建新对象 (int) 并返回其值。但是现在进程 B 附加了这个 DLL。它调用 foo() 但我不明白它data
是如何工作的,因为正在处理'一个内存空间。B 如何能够直接使用它?
采纳答案by selbie
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".
您是对的,默认情况下 DLL 不会跨进程共享内存。在您的示例中,进程 A 和 B 都将获得一个单独的“数据”实例。
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.
如果您的设计希望在使用该 DLL 的所有进程之间共享 DLL 中的全局变量,则可以使用此处所述的共享数据段。您可以通过共享数据段共享预先声明的数组和值类型,但绝对不能共享指针。
回答by j_kubik
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.
你在这里误解了两个不同的概念 - 从这个意义上说,dll 共享内存,所有(永远)不会改变的东西都是共享的(物理上)。它正在节省您的 RAM,因为 DLL 中的大量数据是代码和其他常量数据,因此无论有多少进程使用它,系统都只使用它的一个副本。这在系统级别很重要 - 从应用程序的角度来看,根本没有可见的共享。
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.
然而,这里描述的内部数据不会在进程之间共享——每个进程都有自己的副本。如果您对在进程之间共享内存感兴趣,则需要其他机制。您可能对创建命名共享内存感兴趣。
回答by Darin Dimitrov
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.
进程 B 将拥有自己独立的内存空间,与进程 A 无关。data
变量将在 B 的进程空间内创建。