DLL中的共享内存 [英] Shared memory in DLLs

查看:309
本文介绍了DLL中的共享内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共享内存在DLL中如何工作?



当DLL附加到进程时,它使用与进程相同的内存地址。假设我们在DLL中有以下功能:

  int * data = 0; 
int foo()
{
if(!data)data = new int(random());
return * data;
}

当进程A调用此函数时,它将创建新对象(int),并返回值。
但现在进程B附加这个DLL。它调用foo(),但是我不明白它是如何工作的,因为 data 正在处理'内存空间。 B如何能够直接使用它?

解决方案

你是正确的,默认情况下,DLL不会在进程之间共享内存。在您的示例中,进程A和B都将获得单独的数据实例。



如果您有一个设计,您想要在DLL中共享全局变量在所有使用该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?

解决方案

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中的共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆