本文共 3224 字,大约阅读时间需要 10 分钟。
1.文件映射对象。
2. 创建一个文件映射对象。
3. 对内核对象进行读写操作
windows api:MapViewOfFile
4. 示例
FULL_MAP_NAME 用来标记文件映射对象
server
// Prepare a message to be written to the view. PWSTR pszMessage = (PWSTR)MESSAGE; DWORD cbMessage = (wcslen(pszMessage) + 1) * sizeof(*pszMessage); HANDLE hMapFile = NULL; PVOID pView = NULL; // Create the file mapping object. hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // Use paging file - shared memory NULL, // Default security attributes PAGE_READWRITE, // Allow read and write access 0, // High-order DWORD of file mapping max size MAP_SIZE, // Low-order DWORD of file mapping max size FULL_MAP_NAME // Name of the file mapping object ); if (hMapFile == NULL) { wprintf(L"CreateFileMapping failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } wprintf(L"The file mapping (%s) is created\n", FULL_MAP_NAME); // Map a view of the file mapping into the address space of the current // process. pView = MapViewOfFile( hMapFile, // Handle of the map object FILE_MAP_ALL_ACCESS, // Read and write access 0, // High-order DWORD of the file offset VIEW_OFFSET, // Low-order DWORD of the file offset VIEW_SIZE // The number of bytes to map to view ); if (pView == NULL) { wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } wprintf(L"The file view is mapped\n"); // Write the message to the view. memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage); wprintf(L"This message is written to the view:\n\"%s\"\n", pszMessage);
client
HANDLE hMapFile = NULL; PVOID pView = NULL; // Try to open the named file mapping identified by the map name. hMapFile = OpenFileMapping( FILE_MAP_READ, // Read access FALSE, // Do not inherit the name FULL_MAP_NAME // File mapping name ); if (hMapFile == NULL) { wprintf(L"OpenFileMapping failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } wprintf(L"The file mapping (%s) is opened\n", FULL_MAP_NAME); // Map a view of the file mapping into the address space of the current // process. pView = MapViewOfFile( hMapFile, // Handle of the map object FILE_MAP_READ, // Read access 0, // High-order DWORD of the file offset VIEW_OFFSET, // Low-order DWORD of the file offset VIEW_SIZE // The number of bytes to map to view ); if (pView == NULL) { wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } wprintf(L"The file view is mapped\n"); // Read and display the content in view. wprintf(L"Read from the file mapping:\n\"%s\"\n", (PWSTR)pView);
结果:
【引用】
[1]: 代码地址转载地址:http://dlm.baihongyu.com/