C++使用共享内存

C++使用共享内存

共享内存类

#pragma once
#include 
#include 

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;
};

使用示例-写入数据程序

#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;
}

使用示例-读取数据程序

#include "ShareMem.h"
int main()
{
	ShareMem sh;
	sh.SetMemName("hello_world");
	while (1)
	{
		buf[512];
		sh.readMem(buf, 512);
		Sleep(1000);
	}
	return 0;
}

你可能感兴趣的:(c++,开发语言,共享内存)