Skip to content

Instantly share code, notes, and snippets.

@icecoobe
Created January 13, 2023 05:59
Show Gist options
  • Save icecoobe/38b5a0d904760073da3c596ebcea0e49 to your computer and use it in GitHub Desktop.
Save icecoobe/38b5a0d904760073da3c596ebcea0e49 to your computer and use it in GitHub Desktop.
windows shared memory sample - 2
#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");
while (1)
{
char s[100];
cout << "plz input sth. to be transfered to A process." << endl;
cin >> s;
memcpy((PVOID)pBuffer, s, 100);
}
}
else
{
//打开成功,直接将该内存空间映射到进程的地址空间中
pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
while (1)
{
cout << (char*)pBuffer << endl;
cout << "A process: hit keyboard to receive from B process" << endl;
if (getchar() == 'q')
break;
}
//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