Microsoft KB Archive/89817

= Microsoft Knowledge Base =

How To Specify Shared and Nonshared Data in a DLL
Last reviewed: December 16, 1996

Article ID: Q89817

The information in this article applies to:


 * Microsoft Win32 Application Programming Interface (API) included with: - Microsoft Windows NT versions 3.1, 3.5, 3.51, 4.0 - Microsoft Windows 95 version 4.0

SUMMARY
To have both shared and nonshared data in a dynamic-link library (DLL) which is built with a 32-bit Microsoft C compiler, you need to use the #pragma data_seg directive to set up a new named section. You then must specify the correct sharing attributes for this new named data section in your .DEF file.

The system will try to load the shared memory block created by #pragma data_seg at the same address in each process. However, if the block cannot be loaded into the same memory address, it will be mapped to a different address, but will still be shared. Note, if the memory contains pointers, that this &quot;relocation&quot; will cause the pointers to be invalid. Pointers should not be placed inside shared sections.

MORE INFORMATION
Below is a sample of how to define a named data section in your DLL. The first line directs the compiler to include all the data declared in this section in the .MYSEC data segment. This means that the iSharedVar variable would be considered part of the .MYSEC data segment. By default, data will be nonshared.

Note that you must initialize all data in your named section. The data_seg pragma only applies to initialized data.

The third line, &quot;#pragma data_seg&quot;, directs the compiler to reset allocation to the default data section.

#pragma data_seg(&quot;.MYSEC&quot;) int iSharedVar = 0; #pragma data_seg Below is a sample of the .DEF file that supports the shared and nonshared segments. This definition will set the default section .MYSEC to be shared. The default data section is by default non-shared, so any data not in section .MYSEC will be non-shared.

LIBRARY MyDll SECTIONS .MYSEC READ WRITE SHARED EXPORTS ... NOTE: All section names must begin with a period character ('.') and must not be longer than eight characters, including the period character.