- 共享内存创建步骤
** 1.CreateFileMapping(创建一块内存)
** 2.MapViewOfFile(获取内存中的位置)
** 3.strcpy 在内存地址中写入数据
** 4.使用结束后,关闭销毁。。。
头文件
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <vector>
#include "stdafx.h"
enum USERTYPE{
USER_CLIENT,
USER_SERVER,
};
class ShareMemory{
public:
ShareMemory();
~ShareMemory();
bool InitShareMemory(std::wstring share_name,USERTYPE user_type,int data_size = 4096);
bool WriteData(std::string datas);
bool ReadData(std::string&read_datas);
bool CloseShareMemory();
static ShareMemory* getInstance();
static ShareMemory* m_instance;
private:
HANDLE m_hMapFile;
int m_read_size;
LPVOID m_lpBase;
};
#include "stdafx.h"
#include "ShareMemory.h"
using namespace std;
#define BUF_SIZE 4096
ShareMemory* ShareMemory::m_instance = nullptr;
ShareMemory* ShareMemory::getInstance(){
if (m_instance==nullptr)
{
m_instance = new ShareMemory();
if (m_instance)
{
return m_instance;
}
}
return m_instance;
}
ShareMemory::ShareMemory()
{
m_hMapFile = nullptr;
m_read_size = 0;
m_lpBase = nullptr;
}
ShareMemory::~ShareMemory()
{
if (m_hMapFile!=nullptr)
{
UnmapViewOfFile(m_lpBase);
CloseHandle(m_hMapFile);
}
}
bool ShareMemory::InitShareMemory(std::wstring share_name,USERTYPE user_type,int data_size)
{
m_read_size = data_size;
if (user_type == USER_SERVER)
{
HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,data_size,share_name.c_str());
if (hMapFile == nullptr)
{
cout << "服务端初始化共享内存失败" << endl;
return false;
}
m_hMapFile = hMapFile;
}
else
{
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, NULL, share_name.c_str());
if (hMapFile == nullptr)
{
cout << "客户端初始化共享内存失败" << endl;
return false;
}
m_hMapFile = hMapFile;
}
return true;
}
bool ShareMemory::WriteData(std::string datas)
{
LPVOID lpBase = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (lpBase==nullptr)
{
return false;
}
m_lpBase = lpBase;
strcpy((char*)m_lpBase,datas.c_str());
return true;
}
bool ShareMemory::ReadData(std::string&read_datas)
{
LPVOID lpBase = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (lpBase==nullptr)
{
return false;
}
m_lpBase = lpBase;
char szBuffer[BUF_SIZE] = {0};
strcpy(szBuffer,(char*)m_lpBase);
read_datas = szBuffer;
return true;
}
bool ShareMemory::CloseShareMemory()
{
if (m_hMapFile!=nullptr)
{
UnmapViewOfFile(m_lpBase);
CloseHandle(m_hMapFile);
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
unique_ptr<ShareMemory>sm(new ShareMemory());
std::wstring demo_name = L"ff";
sm->InitShareMemory(demo_name,USER_SERVER);
std::string info_str = "twice";
sm->WriteData(info_str);
system("pause");
return 0;
}