Skip to content

Instantly share code, notes, and snippets.

@icecoobe
Created January 13, 2023 03:49
Show Gist options
  • Save icecoobe/d852292745d9b9b4185796e78a4528c7 to your computer and use it in GitHub Desktop.
Save icecoobe/d852292745d9b9b4185796e78a4528c7 to your computer and use it in GitHub Desktop.
Windows shared memory sample
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strMapName("ShareMemory");
string strComData("This is common data");
LPVOID pBuffer = nullptr;
//打开一个命名为"ShareMemory"的内存映射文件对象
HANDLE hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, strMapName.c_str());
if (NULL == hMap)
{
//打开失败,则创建该内存映射文件对象
hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
strComData.length() + 1,
strMapName.c_str());
if (hMap == nullptr)
{
cout << "CreateFileMapping failed." << endl;
return 0;
}
//将该内存空间映射到进程的地址空间中
pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (pBuffer == nullptr)
{
cout << "MapViewOfFile failed." << endl;
return 0;
}
//向内存中写入数据
strcpy_s((char*)pBuffer, strComData.length() + 1, strComData.c_str());
cout << "[WRITE] " << (char*)pBuffer << endl;
system("pause");
}
else
{
//打开成功,直接将该内存空间映射到进程的地址空间中
pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
cout << "[READ] " << (char*)pBuffer << endl;
}
//解除内存空间映射
if (pBuffer)
::UnmapViewOfFile(pBuffer);
//关闭内存映射文件对象句柄
::CloseHandle(hMap);
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment