先介绍个比较简单的程序,windows下读内存:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
const char FileMaping[255] = "FileMaping";
typedef struct file_map_parameter_t
{
int i_id;
int j_id;
char c_id;
}file_map_parameter_t;
typedef file_map_parameter_t FileMap_t[100];
file_map_parameter_t * m_addr;
bool ReadFileMapping()
{
size_t len = sizeof(FileMaping);
wchar_t* wstr_name = (wchar_t*)malloc((len+1)*sizeof(wchar_t));
HANDLE m_handle = ::OpenFileMapping(FILE_MAP_ALL_ACCESS,false,wstr_name);
if (NULL == m_handle)
{
m_handle = ::CreateFileMapping((HANDLE)INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,
sizeof(FileMap_t),wstr_name);
if( NULL == m_handle)
{
cout<<"共享文件生成失败!"<<endl;
return false;
}
else
{
cout<<"共享文件生成成功!"<<endl;
}
}
m_addr = (file_map_parameter_t*)::MapViewOfFile(m_handle,FILE_MAP_WRITE,0,0,sizeof(FileMap_t));
for (int i = 0;i<20;i++)
{
file_map_parameter_t * m_addrtmp;
m_addrtmp = m_addr + i;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
ReadFileMapping();
return 0;
}
写共享内存:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
const char FileMaping[255] = "FileMaping";
typedef struct file_map_parameter_t
{
int i_id;
int j_id;
char c_id;
}file_map_parameter_t;
typedef file_map_parameter_t FileMap_t[100];
file_map_parameter_t * m_addr;
bool WriteFileMapping()
{
size_t len = sizeof(FileMaping);
wchar_t* wstr_name = (wchar_t*)malloc((len+1)*sizeof(wchar_t));
HANDLE m_handle = ::OpenFileMapping(FILE_MAP_ALL_ACCESS,false,wstr_name);
if (NULL == m_handle)
{
m_handle = ::CreateFileMapping((HANDLE)INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,
sizeof(FileMap_t),wstr_name);
if( NULL == m_handle)
{
cout<<"共享文件生成失败!"<<endl;
return false;
}
else
{
cout<<"共享文件生成成功!"<<endl;
}
}
m_addr = (file_map_parameter_t*)::MapViewOfFile(m_handle,FILE_MAP_WRITE,0,0,sizeof(FileMap_t));
for (int i = 0;i<20;i++)
{
(m_addr + i)->c_id = 'i';
(m_addr + i)->i_id = i;
(m_addr + i)->j_id = 2*i;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
WriteFileMapping();
return 0;
}
这里有一个问题没有解决:
对共享内存的大小问题,比如说上面写的程序是已知共享内存的大小,比如说有20个struct,但是如果
这个大小不是固定的比如类似于一个vector的话该怎么操作呢?
利用boost::interprocess请看
http://blog.csdn.net/great3779/article/details/7226388