简体   繁体   中英

How to use named shared memory?

Today I'm trying to share memory between processes (2 DLLs). For now I would only like to share text in order to do some debugging. I seem to have managed to create the named shared memory and read it, but upon reading the memory seems empty. What could I be doing wrong?

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;
}

The output is:

created shared memory | shared memory:

Instead of BOOL ReadSharedMemory(TCHAR* memName, TCHAR* dat)
use BOOL ReadSharedMemory(TCHAR* memName, std::wstring *szData) and pass pointer to instance of std::wstring instead of TCHAR* .

Also, update szData inside ReadSharedMemory as follows szData->append(dat); before calling UnmapViewOfFile(dat);

Reason is, "Unmapping a mapped view of a file invalidates the range occupied by the view in the address space of the process."

Reference: UnmapViewOfFile function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM