如何使用命名共享内存?

How to use named shared memory?

今天我正在尝试在进程(2 个 DLL)之间共享内存。现在我只想分享文本以便进行一些调试。我似乎设法创建了命名的共享内存并读取了它,但读取后内存似乎是空的。我可能做错了什么?

VOID sharedMemory() {
    if (CreateSharedMemory(TEXT("Global\testMem"), TEXT("hello shared memory"))) {
        out = out + " | created shared memory";
    } else {
        out = out + " | failed to create shared memory";
    }


    wchar_t data[100];
    if (ReadSharedMemory(TEXT("Global\testMem"), data)) {
        std::wstring ws(data);
        out = out + " | shared memory: " + std::string(ws.begin(), ws.end());
    } else {
        out = out + " | no shared memory";
    }
}

BOOL ReadSharedMemory(TCHAR* memName, TCHAR* dat) {
    HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, memName);
    if (hMapFile == NULL) {
        return FALSE;
    }

    dat = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 1024);
    if (dat == NULL) {
        CloseHandle(hMapFile);
        return FALSE;
    }

    UnmapViewOfFile(dat);
    CloseHandle(hMapFile);
    return TRUE;
}

BOOL CreateSharedMemory(TCHAR* memName, TCHAR* data) {
    HANDLE hMapFile = hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, memName);
    if (hMapFile == NULL) {
        return FALSE;
    }

    LPCTSTR pBuf = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 1024);
    if (pBuf == NULL) {
        CloseHandle(hMapFile);
        return FALSE;
    }

    CopyMemory((PVOID)pBuf, data, (_tcslen(data) * sizeof(const wchar_t)));
    UnmapViewOfFile(pBuf);
    return TRUE;
}

输出为:

created shared memory | shared memory:

而不是BOOL ReadSharedMemory(TCHAR* memName, TCHAR* dat)
使用 BOOL ReadSharedMemory(TCHAR* memName, std::wstring *szData) 并将指针传递给 std::wstring 的实例而不是 TCHAR*.

此外,在调用 UnmapViewOfFile(dat);

之前,如下更新 ReadSharedMemory 中的 szData szData->append(dat);

原因是,"Unmapping a mapped view of a file invalidates the range occupied by the view in the address space of the process."

参考:UnmapViewOfFile function