C++使用共享内存
共享内存类
#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;
};
使用示例-写入数据程序
#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;
}