创建命名共享内存

本文提供两个C++示例程序,演示如何使用Windows API创建和打开文件映射对象,进行进程间通信。通过创建文件映射对象并在内存中映射视图,实现数据写入与读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Test1.cpp

#include <Windows.h>
#include <iostream>

using namespace std;

#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]  = TEXT("Message for test file-mapping");

int main()
{
    //-----------------------------------------------------
    // Create File Mapping
    //-----------------------------------------------------
    HANDLE hMapFile;
    hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,   // use paging file
        NULL,                   // default security
        PAGE_READWRITE,         // read/write access
        0,                      // high order DWORD of max object size
        BUF_SIZE,               // low order DWORD of max object size
        szName);                // name of mapping object
    if (hMapFile == NULL)
    {
        cout << "CreateFileMapping failed with error:" 
             << GetLastError() << endl;
        return 1;
    }

    //-----------------------------------------------------
    // Map View of File
    //-----------------------------------------------------
    LPTSTR pBuf = (LPTSTR)MapViewOfFile(
        hMapFile,          // handle to map object
        FILE_MAP_READ | 
        FILE_MAP_WRITE,    // read/write permission
        0,                 // high order DWORD of the file offset 
        0,                 // low order DWORD of the file offset 
        BUF_SIZE);         // number of bytes to map
    if (pBuf == NULL)
    {
        cout << "MapViewOfFile failed with error:" 
             << GetLastError() << endl;
        return 2;
    }

    //-----------------------------------------------------
    // Write File and Read File
    //-----------------------------------------------------
    memcpy(pBuf, szMsg, sizeof(szMsg));
    getchar();
    MessageBox(NULL, pBuf, TEXT("File Mapping Test"), MB_OK);

    //-----------------------------------------------------
    // Unmap View of File and Close File Map Object
    //-----------------------------------------------------
    UnmapViewOfFile(pBuf);
    CloseHandle(hMapFile);

    //-----------------------------------------------------
    // exit
    //-----------------------------------------------------
    system("pause");
    return 0;
}

Test2.cpp

#include <Windows.h>
#include <iostream>

using namespace std;

#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");

int main()
{
    //-----------------------------------------------------
    // Open File Mapping
    //-----------------------------------------------------
    HANDLE hMapFile;
    hMapFile = OpenFileMapping(
        FILE_MAP_READ |
        FILE_MAP_WRITE,    // read/write access
        FALSE,             // handle not inheritable
        szName);           // name of mapping object
    if (hMapFile == NULL)
    {
        cout << "OpenFileMapping failed with error:" 
             << GetLastError() << endl;
        return 1;
    }

    //-----------------------------------------------------
    // Map View of File
    //-----------------------------------------------------
    LPTSTR pBuf = (LPTSTR)MapViewOfFile(
        hMapFile,          // handle to map object
        FILE_MAP_READ |
        FILE_MAP_WRITE,    // read/write permission
        0,                 // high order DWORD of the file offset 
        0,                 // low order DWORD of the file offset 
        BUF_SIZE);         // number of bytes to map
    if (pBuf == NULL)
    {
        cout << "MapViewOfFile failed with error:"
             << GetLastError() << endl;
        return 2;
    }

    //-----------------------------------------------------
    // Write File and Read File
    //-----------------------------------------------------
    *pBuf = TEXT('H');
    MessageBox(NULL, pBuf, TEXT("Test File Mapping"), MB_OK);

    //-----------------------------------------------------
    // Unmap View of File and Close File Map Object
    //-----------------------------------------------------
    UnmapViewOfFile(pBuf);
    CloseHandle(hMapFile);

    //-----------------------------------------------------
    // exit
    //-----------------------------------------------------
    system("pause");
    return 0;
}
### 创建共享内存的过程 在 Windows 操作系统中,创建共享内存涉及几个关键步骤。首先,在进程 `processA` 中需要调用 `CreateFileMapping` 来创建或打开一个已命名的文件映射对象[^1]。 ```cpp #include <windows.h> #include <stdio.h> int main() { HANDLE hMapFile; LPCTSTR pBuf; // Create a file mapping object. hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // 使用分页池 NULL, // 默认的安全属性 PAGE_READWRITE, // 读写权限 0, BUF_SIZE, // 缓冲区大小 szName); // 映射对象名称 if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } } ``` 接着,为了使另一个进程能够访问这段共享内存,需利用 `OpenFileMapping` 函数来获得现有文件映射对象的句柄。 ```cpp // In process B to open the existing named shared memory created by Process A HANDLE hMapFile; char *pBuf; hMapFile = OpenFileMapping( FILE_MAP_ALL_ACCESS, // 请求完全访问权 FALSE, // 不继承句柄 szName); // 名字要与Process A一致 if (hMapFile == NULL) { _tprintf(TEXT("Could not open file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (char*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } ``` 最后一步是使用 `MapViewOfFile` 将文件视图映射到当前进程地址空间内,从而允许对该段共享内存进行读写操作。 一旦完成上述过程,两个独立运行的应用程序就可以通过这块共同分配出来的虚拟存储器交换信息了。值得注意的是,这里展示的例子仅适用于简单的字符串传递场景;对于更复杂的数据结构,则可能还需要考虑同步机制等问题以防止竞态条件的发生。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值