In the software development process, the often encounter needs to share data between processes. A calculation data such as process creation, B process graphically display data. This development approach can separate a large program into separate small program, improve the success rate of software can also be more suitable for team development together, accelerate the development of the software. Before using spokenNamed Pipes way to achieveThe following data sharing on ways to use the file mapping. CreateFileMapping first to use the function to create a file handle to want to share data, then use MapViewOfFile to acquire a shared memory address, and then use the name of the shared OpenFileMapping function to open the file in another process, so that you can achieve different processes to share data.
Function CreateFileMapping, MapViewOfFile the following statement:
WINBASEAPI
__out
HANDLE
WINAPI
CreateFileMappingA(
__in HANDLE hFile,
__in_opt LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
__in DWORD flProtect,
__in DWORD dwMaximumSizeHigh,
__in DWORD dwMaximumSizeLow,
__in_opt LPCSTR lpName
);
WINBASEAPI
__out
HANDLE
WINAPI
CreateFileMappingW(
__in HANDLE hFile,
__in_opt LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
__in DWORD flProtect,
__in DWORD dwMaximumSizeHigh,
__in DWORD dwMaximumSizeLow,
__in_opt LPCWSTR lpName
);
#ifdef UNICODE
#define CreateFileMapping CreateFileMappingW
#else
#define CreateFileMapping CreateFileMappingA
#endif // !UNICODE
WINBASEAPI
__out
LPVOID
WINAPI
MapViewOfFile(
__in HANDLE hFileMappingObject,
__in DWORD dwDesiredAccess,
__in DWORD dwFileOffsetHigh,
__in DWORD dwFileOffsetLow,
__in SIZE_T dwNumberOfBytesToMap
);
hFileIt is to create a handle to shared files.
lpFileMappingAttributesFile sharing attributes.
flProtectWhen a file is read-write mapping file attributes.
dwMaximumSizeHighFile sharing is the size of the high byte.
dwMaximumSizeLowFile sharing is the size of the low byte.
lpNameShared file object name.
hFileMappingObjectShared file object.
dwDesiredAccessFile sharing attributes.
dwFileOffsetHighIt is the offset address of the file sharing area.
dwFileOffsetLowIt is the offset address of the file sharing area.
dwNumberOfBytesToMapShared data length.
Examples of calling the function as follows:
//File Sharing.
void FileMapping(void)
{
// Open the file sharing of objects.
m_hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE,_T("TestFileMap"));
if (m_hMapFile)
{
// display file data sharing.
LPTSTR lpMapAddr = (LPTSTR)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS,
0,0,0);
OutputDebugString(lpMapAddr);
}
else
{
// Create a shared file.
m_hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF,NULL,
PAGE_READWRITE,0,1024,_T("TestFileMap"));
// copy data to a shared file.
LPTSTR lpMapAddr = (LPTSTR)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS,
0,0,0);
std::wstring strTest(_T("TestFileMap"));
wcscpy(lpMapAddr,strTest.c_str());
FlushViewOfFile(lpMapAddr,strTest.length()+1);
}
}