# Pragma data_seg is generally used in DLL. The DLL address space can be mapped by multiple processes at the same time. When a process is loaded, the DLL address space is mapped to the private virtual space of the process, when all data segments are only used for reading, the data is one copy in the memory, and cow is used after Win2000, that is, copy on write. When writing data, the data is copied as a separate copy. In this way, data cannot be shared in DLL. To share data, you need to use # pragma data_dataseg to define a shared data segment.
1. # pragma data_seg Introduction
Use # pragma data_seg to create a data segment with a name and define the shared data. The specific format is:
# Pragma data_seg ("shared") // The Name Of The shared segment cannot exceed 8 characters. Otherwise, it will be truncated.
Hwnd sharedwnd = NULL; // share data, and the data between the segments can be shared by all the processes that load the DLL.
# Pragma data_seg ()
# Pragma comment (linker, "/section: shared, RWS") // tells the linker that shared segments are readable and writable and shared.
The most important thing is that the global variables in this data segment can be shared by multiple processes. Otherwise, the global variables in the DLL cannot be shared among multiple processes.
2. Shared data must be initialized. Otherwise, the Microsoft compiler will put uninitialized data in the. BSS segment, leading to failure in sharing among multiple processes.
3. What you call correct results is an illusion. If you write this in a DLL:
# Pragma data_seg ("mydata ")
Int g_value; // note that the global is not initialized.
# Pragma data_seg ()
DLL provides two interface functions:
Int getvalue ()
{
Return g_value;
}
Void setvalue (int n)
{
G_value = N;
}
Then start two processes A and B, and a and B call this DLL. If a calls setvalue (5), B then calls int M = getvalue (); the m value is not necessarily 5, but an undefined value. Because the global data in DLL is private and cannot be shared for every process that calls it. If you initialize g_value, g_value will be put into the mydata segment. In other words, if a calls setvalue (5); B then calls int M = getvalue (); then the value of m must be 5! This enables cross-process data communication!
This release can be used to ensure that an application in the current system is started only once.