Windows 内存映射
Windows 内存映射
NiuYoohoo 发表于7个月前
Windows 内存映射
  • 发表于 7个月前
  • 阅读 46
  • 收藏 1
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

创建和打开内存映射

class MemoryShare
{
public:
	static HANDLE CreateMemoryMap(std::string id, size_t shared_mem, void* &map_buf)
	{
		return MemoryShare::CreateMemoryMap(id, shared_mem, "", map_buf);
	}
	static HANDLE CreateMemoryMap(std::string id, size_t shared_mem, std::string file, void* &map_buf)
	{
		HANDLE hFile = NULL;
		HANDLE hMap = NULL;
		if (!file.empty())
			hFile = CreateFileA(file.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | 
			FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

		if (hFile)
		{
			hMap = CreateFileMappingA(hFile, NULL, PAGE_READWRITE, 0, shared_mem, id.c_str());
		}
		else
		{
			hMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, shared_mem, id.c_str());
		}
		if (hMap == NULL)
		{
			if (hFile)
				CloseHandle(hFile);
			return false;
		}

		map_buf = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
		if (!map_buf)
		{
			if (hFile)
				CloseHandle(hFile);
			CloseHandle(hMap);
			hMap = NULL;
			return false;
		}
		if (hFile)
			CloseHandle(hFile);
		return hMap;

	}
	static bool OpenMemoryMap(std::string id, size_t map_size,void* &map_buf)
	{
		HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, id.c_str());
		if (!hMap)
		{
			return false;
		}
		map_buf = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, map_size);
		if (!map_buf)
		{
			CloseHandle(hMap);
			return false;
		}
		CloseHandle(hMap);
		return true;
	}
	static void CloseMemoryMap(void* base_map)
	{
		if (base_map)
			UnmapViewOfFile(base_map);
	}

};

Example

void* pto = NULL;
HANDLE hMem = MemoryShare::CreateMemoryMap("yoohoo", 3000, "G:/a.txt", pto);
if (hMem)
{
	memcpy(pto, "123456789", 10);
}

void* pmap = NULL;

if (MemoryShare::OpenMemoryMap("yoohoo", 256, pmap))
{
	cout << (char*)pmap;
}

getchar();
if (hMem)
	CloseHandle(hMem);
MemoryShare::CloseMemoryMap(pmap);

 

标签: 内存映射
共有 人打赏支持
粉丝 2
博文 45
码字总数 18114
×
NiuYoohoo
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: