您的位置:首页 > 其它

DLL在多个相同或不同的exe之间共享静态数据

2012-09-06 17:25 197 查看
在Windows via C/C++的chap17中讲到,在通常情况下,一个dll文件同时被多处关联使用或exe文件同时有多个实例在运行,通过memory mapping在内存中实际只存在一份dll或exe的数据。如果dll或exe中的全局变量被修改,则通过copy-on-write,将被修改的内容所在page在内存中复制出一份,并将引用关联改为新的page。这样就不会影响到其他使用同一份page的程序,发生修改的进程中对应内容的地址修改为新的page地址。这样在设计dll时应尽量避免使用全局变量,否则根据copy-on-write的规则,很可能造成内存中存在多份内容大体相同,而仅有少量修改所导致的内存复制。

如果需要将dll或exe中的全局变量在多个实例中共享,可以采用以下方法。
// Tell the compiler to put this initialized variable in its own Shared // section so it is shared by all instances of this application. #pragma data_seg("Shared") volatile LONG g_lApplicationInstances = 0; #pragma data_seg() // Tell the linker to make the Shared section // readable, writable, and shared. #pragma comment(linker, "/Section:Shared,RWS")

本文转自:http://www.mindair.net/2011/03/02/dll及多个相同exe之间共享静态数据/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: