SharedMemory.h
#pragma once
#include <string>
#include <windows.h>
#include <conio.h>
#include <iostream>
class SharedMemory
{
public:
SharedMemory();
~SharedMemory();
bool open(const char* mapFileName,int size=256);
bool create(const char* mapFileName,int size=256);
const wchar_t* GetWC(const char* c);
void close();
void send(const char* data);
std::string receive();
private:
HANDLE hMapFile;
LPTSTR pBuf;
};
SharedMemory.cpp
#include "SharedMemory.h"
#include "comutil.h"
SharedMemory::SharedMemory()
{
}
SharedMemory::~SharedMemory()
{
}
bool SharedMemory::open(const char* mapFileName,int size)
{
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, GetWC(mapFileName));
if (NULL == hMapFile)
{
std::cout << "open fail" << std::endl;
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, size);
if (NULL == pBuf)
{
std::cout << "MapViewOfFile fail" << std::endl;
CloseHandle(hMapFile);
hMapFile = NULL;
return false;
}
return true;
}
bool SharedMemory::create(const char* mapFileName, int size/*=256*/)
{
hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, GetWC(mapFileName));
if (NULL == hMapFile)
{
std::cout << "create fail" << std::endl;
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, size);
if (NULL == pBuf)
{
std::cout << "MapViewOfFile fail" << std::endl;
CloseHandle(hMapFile);
hMapFile = NULL;
return false;
}
return true;
}
const wchar_t* SharedMemory::GetWC(const char* c)
{
const size_t cSize = strlen(c) + 1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs(wc, c, cSize);
return wc;
}
void SharedMemory::close()
{
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
}
void SharedMemory::send(const char* data)
{
std::cout <<"data:"<< data << std::endl;
CopyMemory((void*)pBuf, GetWC(data), strlen(data)*sizeof(TCHAR));
}
std::string SharedMemory::receive()
{
std::string str;
bstr_t b(pBuf);
const char *buf = b;
for (int i = 0; i < strlen(buf); i++)
{
str+=buf[i];
}
return str;
}