# DLL之共享数据段(转)

700人阅读 评论(0)
 在主文件中，用#pragma data_seg建立一 个新的数据段并定义共享数据，其具体格式为：  #pragma data_seg （"shareddata") //名称可以                        //自己定义，但必须与下面的一致。 HWND sharedwnd=NULL;//共享数据 #pragma data_seg()

在Win16环境中，DLL的全局数据对每个载入它的进程来说都是相同的；而在Win32环境中，情况却发生了变化，DLL函数中的代码所创建的任何对象（包括变量）都归调用它的线程或进程所有。当进程在载入DLL时，操作系统自动把DLL地址映射到该进程的私有空间，也就是进程的虚拟地址空间，而且也复制该DLL的全局数据的一份拷贝到该进程空间。也就是说每个进程所拥有的相同的DLL的全局数据，它们的名称相同，但其值却并不一定是相同的，而且是互不干涉的。

#pragma data_seg预处理指令用于设置共享数据段。例如：
#pragma data_seg("SharedDataName")
HHOOK hHook=NULL;   //必须在定义的同时进行初始化!!!!
#pragma data_seg()

Win32 DLLs are mapped into the address space of the calling process. By default, each process using a DLL has its own instance of all the DLLs global and static variables. (注意: 即使是全局变量和静态变量也都不是共享的!)  If your DLL needs to share data with other instances of it loaded by other applications, 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.

Here is an example of using the data_seg pragma:

#pragma data_seg (".myseg")
int i = 0;
char a[32] = "hello world";
#pragma data_seg()

data_seg can be used to create a new named section (.myseg in this example). The most typical usage is to call the data segment .shared for clarity. 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中指定！)

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.

• 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.

• 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.

• 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.

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：443063次
• 积分：4970
• 等级：
• 排名：第5682名
• 原创：75篇
• 转载：97篇
• 译文：0篇
• 评论：24条
文章分类
评论排行
最新评论