windows c++共享内存

#include <iostream>
#include <Windows.h>
#include <string>
int main() {
	const wchar_t* mapName = L"Local\\MySharedMemory";
	const size_t buffSize = 256;

	//创建共享内存对象 得到一个内核句柄handle
	HANDLE hMapFile = CreateFileMapping(
		INVALID_HANDLE_VALUE,
		NULL,
		PAGE_READWRITE,
		0,
		buffSize,
		mapName);
	if (hMapFile == NULL)
	{
		int code = GetLastError();
		return 0;
	}

	//将内核对象映射到内存地址 
	void* pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, buffSize);
	if (pBuf == NULL) {
		CloseHandle(hMapFile);
		return 0;
	}

	//向共享内存写入数据 
	int index = 0;
	while (1) {
		memset(pBuf, 0, buffSize);
		std::string message = "hello world writer process "+std::to_string(index);
		memcpy(pBuf, message.c_str(), message.size() + 1);
		index++;
		Sleep(1000);
	}

	UnmapViewOfFile(pBuf);
	CloseHandle(hMapFile);
	return 0;
}
#include <iostream>
#include <Windows.h>
#include <string>
int main()
{
	const wchar_t* mapName = L"Local\\MySharedMemory";
	const size_t buffSize = 256;
	//打开一个共享内存的映射对象
	HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapName);
	if (hMapFile == NULL)
	{
		return -1;
	}

	void* pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, buffSize);
	if (pBuf == NULL)
	{
		CloseHandle(hMapFile);
		return -1;
	}

	while (1) {
		char message[buffSize]{ 0 };
		memcpy(message, pBuf, buffSize - 1);
		std::cout << message << std::endl;
		Sleep(1000);
	}

	UnmapViewOfFile(pBuf);
	CloseHandle(hMapFile);
	return 0;
}

 

posted @   caoruipeng  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示