今天我尝试在进程之间共享内存(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;
}
输出结果为:
创建共享内存|共享内存:
答案 0 :(得分:0)
而不是BOOL ReadSharedMemory(TCHAR* memName, TCHAR* dat)
使用BOOL ReadSharedMemory(TCHAR* memName, std::wstring *szData)
并将指针传递给std::wstring
的实例,而不是TCHAR*
。
另外,在调用szData
ReadSharedMemory
内更新szData->append(dat);
,如下所示UnmapViewOfFile(dat);
原因是,"取消映射文件的映射视图会使进程的地址空间中视图占用的范围无效。"