85 lines
2.5 KiB
C++
85 lines
2.5 KiB
C++
|
|||
|
|
#include <windows.h>
|
||
|
|
#include <string>
|
||
|
|
#define memSize 512
|
||
|
|
bool writeSharedMem(std::string memName,std::string text)
|
||
|
|
{
|
||
|
|
char* memNameChar = (char*)(memName.c_str());
|
||
|
|
HANDLE hMapFile = OpenFileMapping(
|
||
|
|
FILE_MAP_ALL_ACCESS, // 读/写访问
|
||
|
|
FALSE, // 句柄不继承
|
||
|
|
memNameChar // 共享内存对象的名称
|
||
|
|
);
|
||
|
|
|
||
|
|
if (hMapFile == NULL)
|
||
|
|
{
|
||
|
|
hMapFile = CreateFileMapping(
|
||
|
|
INVALID_HANDLE_VALUE, // 使用分页文件
|
||
|
|
NULL, // 默认安全性
|
||
|
|
PAGE_READWRITE, // 读/写访问
|
||
|
|
0, // 最大对象大小(高位32位)
|
||
|
|
memSize, // 最大对象大小(低位32位)
|
||
|
|
memNameChar // 共享内存对象的名称
|
||
|
|
);
|
||
|
|
}
|
||
|
|
if (hMapFile == NULL)
|
||
|
|
return false;
|
||
|
|
|
||
|
|
char* pBuf = (char*)MapViewOfFile(
|
||
|
|
hMapFile, // 共享内存对象的句柄
|
||
|
|
FILE_MAP_ALL_ACCESS, // 读/写权限
|
||
|
|
0,
|
||
|
|
0,
|
||
|
|
memSize
|
||
|
|
);
|
||
|
|
if (pBuf == NULL) {
|
||
|
|
std::cerr << "Could not map view of file (" << GetLastError() << ")." << std::endl;
|
||
|
|
CloseHandle(hMapFile);
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
strcpy(pBuf, text.c_str());
|
||
|
|
UnmapViewOfFile(pBuf);
|
||
|
|
//CloseHandle(hMapFile);
|
||
|
|
}
|
||
|
|
std::string readSharedMem(std::string memName)
|
||
|
|
{
|
||
|
|
char* memNameChar = (char*)(memName.c_str());
|
||
|
|
HANDLE hMapFile = OpenFileMapping(
|
||
|
|
FILE_MAP_ALL_ACCESS, // 读/写访问
|
||
|
|
FALSE, // 句柄不继承
|
||
|
|
memNameChar // 共享内存对象的名称
|
||
|
|
);
|
||
|
|
if (hMapFile == NULL)
|
||
|
|
{
|
||
|
|
std::cerr << "Could not open file mapping object (" << GetLastError() << ")." << std::endl;
|
||
|
|
return "notFound";
|
||
|
|
}
|
||
|
|
char* pBuf = (char*)MapViewOfFile(
|
||
|
|
hMapFile, // 共享内存对象的句柄
|
||
|
|
FILE_MAP_ALL_ACCESS, // 读/写权限
|
||
|
|
0,
|
||
|
|
0,
|
||
|
|
memSize
|
||
|
|
);
|
||
|
|
std::string reuslt = pBuf;
|
||
|
|
UnmapViewOfFile(pBuf);
|
||
|
|
//CloseHandle(hMapFile);
|
||
|
|
return reuslt;
|
||
|
|
}
|
||
|
|
bool releaseSharedMem(std::string memName)
|
||
|
|
{
|
||
|
|
char* memNameChar = (char*)(memName.c_str());
|
||
|
|
HANDLE hMapFile = OpenFileMapping(
|
||
|
|
FILE_MAP_ALL_ACCESS, // 读/写访问
|
||
|
|
FALSE, // 句柄不继承
|
||
|
|
memNameChar // 共享内存对象的名称
|
||
|
|
);
|
||
|
|
if (hMapFile == NULL)
|
||
|
|
{
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
CloseHandle(hMapFile);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
#pragma once
|