无法映射共享内存

Cannot map shared memory

我想在两个进程之间创建一个共享内存。因此,我只是从微软页面复制了片段:

片段 1:

#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");

void initSharedMem() {
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = CreateFileMapping(
    INVALID_HANDLE_VALUE,    // use paging file
    NULL,                    // default security
    PAGE_READWRITE,          // read/write access
    0,                       // maximum object size (high-order DWORD)
    BUF_SIZE,                // maximum object size (low-order DWORD)
    szName);                 // name of mapping object

if (hMapFile == NULL) {
    MessageBox(0, "Could not create file mapping object", "Error", 0);
    return;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile,   // handle to map object
    FILE_MAP_ALL_ACCESS, // read/write permission
    0,
    0,
    BUF_SIZE);

if (pBuf == NULL) {
    MessageBox(0, "Could not map view of file", "Error", 0);
    CloseHandle(hMapFile);

    return;
}


CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);

MessageBox(0, "Done init shared mem", "Done", 0);
return;
}

片段 2(其他过程):

#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");

void readSharedMem() {
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = OpenFileMapping(
    FILE_MAP_ALL_ACCESS,   // read/write access
    FALSE,                 // do not inherit the name
    szName);               // name of mapping object

if (hMapFile == NULL) {
    MessageBox(0, L"Error", L"Could not open file mapping object", 0);
    return;
}

pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
    FILE_MAP_ALL_ACCESS,  // read/write permission
    0,
    0,
    BUF_SIZE);

if (pBuf == NULL) {
    MessageBox(0, L"Error", L"Could not map file", 0);

    CloseHandle(hMapFile);

    return;
}

MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);

return;

MessageBox(0, L"Done", L"SharedMemoryDone", 0);
}

我在进程A中调用了第一个函数,得到了done消息。但是当我之后调用 readSharedMem 函数时,我收到错误消息 "Could not open file mapping object".

我做错了什么?

I call the first function in process A, and get the done message.

在完成消息出现时,文件映射对象已经关闭,因此不再存在。

But when I call the readSharedMem function afterwards I get the error message "Could not open file mapping object".

你离开得太晚了!您需要在文件映射对象仍然存在时打开它。这大概就是第一个片段中对 _getch 的调用的目的;你应该在那个时候 运行 另一个程序,然后再按一个键继续。