DLL 中的共享内存
DLL 中的共享内存是如何工作的?
当DLL附加到进程时,它使用与进程相同的内存地址。假设 DLL 中有以下函数:
int * data = 0;
int foo()
{
if (!data) data = new int(random());
return *data;
}
当进程 A 调用此函数时,它会创建新对象 (int) 并返回其值。 但现在进程 B 附加了这个 DLL。它调用 foo() 但我不明白它是如何工作的,因为 data
正在进程' 内存空间中。 B如何能够直接使用它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的,DLL 默认情况下不跨进程共享内存。在您的示例中,进程 A 和 B 都会获得一个单独的“数据”实例。
如果您的设计希望 DLL 中的全局变量在使用该 DLL 的所有进程之间共享,则可以使用共享数据段,如下所述 此处。您可以通过共享数据段共享预先声明的数组和值类型,但绝对不能共享指针。
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.
您在这里误解了两个不同的概念 - dll 在这个意义上共享内存,即所有不会(永远)改变的东西都是共享的(物理上)。它节省了你的RAM,因为DLL中的大量数据是代码和其他常量数据,所以系统只使用它的一份副本,无论有多少进程使用它。这在系统级别很重要 - 从应用程序的角度来看,根本没有可见的共享。
然而,像这里描述的那样的内部数据不在进程之间共享——每个进程都有自己的副本。如果您有兴趣在进程之间共享内存,则需要其他机制。您可能对创建命名感兴趣共享内存。
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 的进程空间内创建。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.