C++使用共享内存

C++使用共享内存

共享内存类

cpp 复制代码
#pragma once
#include <iostream>
#include <Windows.h>

class ShareMem
{
public:
	ShareMem()
	{
		pBuf = NULL;
	}
	~ShareMem()
	{
		if (pBuf != NULL)
		{
			UnmapViewOfFile(pBuf);
		}
		CloseHandle(hMapFile);
	}

	void SetMemName(char* name)
	{
		m_name = name;
	}

	int WriteMem(void* arg, int len)
	{
		hMapFile = CreateFileMapping(
			INVALID_HANDLE_VALUE,   // 使用物理内存
			NULL,                   // 默认安全级别
			PAGE_READWRITE,         // 可读可写
			0,                      // 高位文件大小
			1024,                   // 低位文件大小
			TEXT(m_name));   // 共享内存名称
		if (hMapFile == NULL)
		{
			std::cout << "CreateFileMapping failed, error code: " << GetLastError() << std::endl;
			return -1;
		}

		pBuf = (char*)MapViewOfFile(
			hMapFile,               // 共享内存句柄
			FILE_MAP_ALL_ACCESS,    // 可读可写
			0,
			0,
			1024);                  // 共享内存大小

		if (pBuf == NULL)
		{
			std::cout << "MapViewOfFile failed, error code: " << GetLastError() << std::endl;
			return -1;
		}

		CopyMemory((PVOID)pBuf, arg, len);

		std::cout << "Write data to shared memory successfully!" << std::endl;


		return 0;
	}

	int readMem(void* readBuf, int len)
	{
		hMapFile = OpenFileMapping(
			FILE_MAP_ALL_ACCESS,    // 可读可写
			FALSE,                  // 不继承句柄
			TEXT(m_name));   // 共享内存名称

		pBuf = (char*)MapViewOfFile(
			hMapFile,               // 共享内存句柄
			FILE_MAP_ALL_ACCESS,    // 可读可写
			0,
			0,
			1024);                  // 共享内存大小

		if (pBuf != NULL)
		{
			readBuf = pBuf;
			std::cout << "Read data from shared memory: " << (char*)pBuf << std::endl;
		}

		return 0;
	}

private:
	HANDLE hMapFile;
	char* pBuf;
	char* m_name;
};

使用示例-写入数据程序

cpp 复制代码
#include "ShareMem.h"
int main()
{
	ShareMem sh;
	sh.SetMemName("hello_world");
	char buf[512] = "hello world aaaabbbbccccdddd";
	sh.WriteMem(buf, 512);
	system("pause");
	return 0;
}

使用示例-读取数据程序

cpp 复制代码
#include "ShareMem.h"
int main()
{
	ShareMem sh;
	sh.SetMemName("hello_world");
	while (1)
	{
		buf[512];
		sh.readMem(buf, 512);
		Sleep(1000);
	}
	return 0;
}
相关推荐
郑州光合科技余经理4 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 小时前
matlab画图工具
开发语言·matlab
dustcell.5 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame5 小时前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 小时前
信号量和信号
linux·c++
多恩Stone5 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月5 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
蜡笔小马6 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237176 小时前
C语言-数组练习进阶
c语言·开发语言·算法