c++文件映射

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值