DLL 中的共享内存

发布于 2024-12-09 02:18:35 字数 316 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青春有你 2024-12-16 02:18:35

你是对的,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.

厌倦 2024-12-16 02:18:35

您在这里误解了两个不同的概念 - 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.

马蹄踏│碎落叶 2024-12-16 02:18:35

进程 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文