(Owed by: 春夜喜雨 http://blog.csdn.net/chunyexiyu 转载请标明来源)
参考文档: http://blog.csdn.net/xuyuefei1988/article/details/10391097
参考文档: http://blog.csdn.net/hczhiyue/article/details/6785773
参考文档: 百度百科-#pragma
同一个dll被多个进程使用的时候,在大多数情况下,各个进程使用dll和独自使用dll效果是相同的。
因为对于dll中的局部变量是写入到进程的堆栈中的,全局变量也被操作系统为每个线程copy一份各自使用。
you can use either of the following approaches:
· Create named data sections using the data_seg pragma.
· Use memory mapped files. See the Win32 documentation about memory mapped files.
通过声明共享数据段的方法:
#pragma data_seg (".MyShareSeg")
int i = 0; //共享数据必须初始化,否则微软编译器会把没有初始化的数据放到.BSS段中,从而导致多个进程之间的共享行为失败。
char a[32] = "hello world";
#pragma data_seg()
#pragma comment(linker,"/SECTION:.MyShareSeg,RWS")
You then must specify the correct sharing attributes for this new named data section in your .def file or with the linker option /SECTION:.MYSEC,RWS. (这个编译参数既可以使用pragma指令来指定,也可以在VC的IDE中指定! #pragma comment(linker,"/SECTION:.MyShareSeg,RWS") )
There are restrictions to consider before using a shared data segment:
· Any variables in a shared data segment must be statically initialized. In the above example, i is initialized to 0 and a is 32 characters initialized to hello world. (必须初始化变量)
· All shared variables are placed in the compiled DLL in the specified data segment. Very large arrays can result in very large DLLs. This is true of all initialized global variables. (变量存储在dll指定的segment中,使用array会导致dll比较大。)
· Never store process-specific information in a shared data segment. Most Win32 data structures or values (such as HANDLEs) are really valid only within the context of a single process. (不要在segment中存储进程信息,大多数win32程序中例如handle等仅在自己进程内有效。)
· Each process gets its own address space. It is very important that pointers are never stored in a variable contained in a shared data segment. A pointer might be perfectly valid in one application but not in another. (不要在segment中存储指针,因为每个进程有自己的地址信息,指针仅在进程内是有效的。)
· It is possible that the DLL itself could get loaded at a different address in the virtual address spaces of each process. It is not safe to have pointers to functions in the DLL or to other shared variables. (在segment中使用函数指针是不安全的,因为有可能dll被进程加载在一个虚拟地址中。)
共享数据段,一般就是用在dll的内存共享上。共享数据段被编译到dll中去,在操作系统加载dll时,作为和程序代码段类似的全局使用。这才导致共享数据段可以在多个进程调用dll时的共用。
同时共享数据段越大,编译出的dll就会越大。
对于exe程序来说,使用共享数据段的话,同一个程序多次执行也有类似效果,不过这种共享通常意义不大的。
注意: 根据使用发现
1. 当所有引用dll的程序都关闭的时候,dll会被操作系统卸载,也导到共享数据段就没有了。重新打开程序时,dll加载,共享数据段再次初始化并存在。
2. 共享数据段是在同一个机器中共享,并且dll必须是同一个,名称必须一样。例如,dll复制一份并重命名,就相当于不是同一个dll了。
(Owed by: 春夜喜雨 http://blog.csdn.net/chunyexiyu 转载请标明来源)