Windows进程通信--共享内存(三)

基于前面的文章,这次对共享内存简单的封装一下,使得共享内存的使用更为容易。

为了代码的简单,这次封装的也都是同步的共享内存,如果需要支持异步的话,引入线程池(ShareMemory::writeData里面的功能放在线程里面来做)即可。也不是特别复杂。

代码如下:

ShareMemoryHelper.h

#ifndef SHAREMEMORYHELER_H
#define SHAREMEMORYHELER_H

#include 
#include 
class ShareMemory;

class ShareMemoryHelper
{
public:
	ShareMemoryHelper(const std::wstring &uuid);
	~ShareMemoryHelper();

	void writeData(char *pData, unsigned int nLength);

private:
	void receiveData(unsigned char *pData, int nLength);

private:
	std::shared_ptr m_ptrReadShareMemory;
	std::shared_ptr m_ptrWriteShareMemory;
};

#endif

ShareMemoryHelper.cpp

#include "stdafx.h"
#include "ShareMemoryHelper.h"
#include "ShareMemory.h"


ShareMemoryHelper::ShareMemoryHelper(const std::wstring &uuid)
{
	std::wstring readUuid = uuid + L"_readShareMemory";
	m_ptrReadShareMemory = std::make_shared(readUuid);
	m_ptrReadShareMemory->registeReceiver(std::bind(&ShareMemoryHelper::receiveData, this, std::placeholders::_1, std::placeholders::_2));

	std::wstring writeUuid = uuid + L"_writeShareMemory";
	m_ptrWriteShareMemory = std::make_shared(writeUuid);
}


ShareMemoryHelper::~ShareMemoryHelper()
{
}

void ShareMemoryHelper::writeData(char *pData, unsigned int nLength)
{
	m_ptrWriteShareMemory->writeData(pData, nLength);
}

void ShareMemoryHelper::receiveData(unsigned char *pData, int nLength)
{
	//通知外部程序接收到其他进程的数据
	//@todo...
}

 

你可能感兴趣的:(C++)