Windows 程序设计 第二十一章 DLL中共享内存数据

P964--973


Sharing Data Among STRPROG Instances

Windows erects a wall around the address space of a Win32 process. Normally, data in an address space is private, invisible to other processes. But running multiple instances of STRPROG shows that STRLIB has no trouble sharing its data with all instances of the program. When you add or delete a string in a STRPROG window, the change is immediately reflected in the other windows.

STRLIB shares two variables among all its instances: an array of strings and an integer indicating the number of valid strings stored. STRLIB keeps these two variables in a special section of memory that it designates as shared:

#pragma data_seg ("shared")
int   iTotal = 0 ;
WCHAR szStrings [MAX_STRINGS][MAX_LENGTH + 1] = {'\0'} ;
#pragma data_seg ()

The first #pragma statement creates the data section, here named shared. You can name the section whatever you wish. All initialized variables after the#pragma go into the shared section. The second #pragma statement marks the end of the section. It's important to specifically initialize the variables; otherwise, the compiler puts them in the normal uninitialized section rather than in shared.

The linker has to be told about shared. In the Project Settings dialog box, select the Link tab. In the Project Options field for STRLIB (in both the Release and Debug configurations), include the following linker argument:

/SECTION:shared,RWS

The RWS letters indicate that the section has read, write, and shared attributes. Or you can specify the linker option directly in the DLL source code, as is done in STRLIB.C:

#pragma comment(linker,"/SECTION:shared,RWS")

The shared memory section allows the iTotal variable and the szStrings array of strings to be shared among all instances of STRLIB. Because MAX_STRINGS is equal to 256 and MAX_LENGTH is equal to 63, the shared memory section is 32,772 bytes in length---the 4 bytes required for the iTotal variable and 128 bytes each for the 256 pointers.

Using a shared memory section is probably the easiest way to share data among multiple applications. If you need to dynamically allocate shared memory space, you should look into the use of file mapping objects, documented at/Platform SDK/Windows Base Services/Interprocess Communication/File Mapping




你可能感兴趣的:(Windows 程序设计 第二十一章 DLL中共享内存数据)