Share via


How do I share data in my DLL with an application or with other DLLs?

OverviewHow Do IFAQDetailsSample

Win32 DLLs are mapped into the address space of the calling process. By default, each process using a DLL has its own instance of the DLL global and static variables. If your DLL needs to share data with other Win32 DLLs loaded by a different application or with different mappings of the same DLL, then you can use either of the following approaches:

  • Create named data sections using the #pragma statement.

  • Use memory-mapped files.

To set up a new named section, use the #pragma data_seg directive. You then must specify the correct sharing attributes for this new named data section in your .DEF file. For more information about creating named data sections, see the following Knowledge Base articles:

  • "How to Share Data Between Different Mappings of a DLL" (Q125677).

  • "Specifying Shared and Nonshared Data in a DLL" (Q100634).

  • "How to Specify Shared and Nonshared Data in a DLL" (Q89817).

  • "Sharing All Data in a DLL" (Q109619).

However, if you need to share a C++ class instance, you should use a memory-mapped file, because each time a process attaches to the DLL, the constructor for the object is called. For example:

#pragma  data_seg(".myseg")
  _declspec(dllexport) CTest Counter1(0);
  _declspec(dllexport) short Counter2 = 0;
#pragma data_seg()

Assume that the variables Counter1 and Counter2 are incremented in a function in the DLL. The value of Counter2 increases as expected, but on each process attach, the constructor for Counter1 is called reinitializing it to zero. In order to share Counter1, you must use a memory-mapped file. For more information about memory-mapped files, see in the Win32 SDK documentation.