我正在尝试将 std::map 存储在共享内存段上。但我无法恢复地图。
我创建共享内存段(使用下面的类)并将映射地址分配给它。
但是当我试图恢复它时,我得到了一个错误的指针。
以下是一些代码片段:
// This is in my header file
CSharedMem * shMem;
// This is in my cpp file - inside my class constructor
shMem = new CSharedMem("MyShMem", 16536);
void * ptr = shMem->GetAddress();
std::map<int,int> myMap;
ptr = &myMap;
shMem-ReleaseAddress();
// This is inside another function
void * ptr = shMem->GetAdress();
std::map<int,int> myMap = *static_cast<std::map<int,int> *> (ptr);
有人有线索吗?
CSharedMem 类头文件:
#pragma once
#include <string>
class CSharedMem
{
public:
CSharedMem(const std::string& name, std::size_t size);
~CSharedMem();
void* GetAddress() const;
void ReleaseAddress();
bool IsShared() const;
private:
bool shared_;
void* address_;
private:
void* shm_;
void* mtx_;
};
cpp文件:
#include "StdAfx.h"
#include "SharedMem.h"
#include <windows.h>
CSharedMem::CSharedMem(const std::string& name, std::size_t size)
: shared_(false),
address_(NULL)
{
shm_ = CreateFileMapping(INVALID_HANDLE_VALUE,
NULL, PAGE_READWRITE,
0,
static_cast<DWORD>(size),
name.c_str() );
if( shm_ == INVALID_HANDLE_VALUE )
throw std::exception("Failed to allocate shared memory.");
if( GetLastError() == ERROR_ALREADY_EXISTS )
shared_ = true;
address_ = MapViewOfFile(shm_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if( address_ == NULL )
throw std::exception("Failed to map shared memory.");
if( !shared_ )
std::memset(address_, 0, size);
mtx_ = CreateMutex(NULL, FALSE, (name + "MTX").c_str());
if( mtx_ == INVALID_HANDLE_VALUE )
throw std::exception("Failed to create shared mutex.");
}
CSharedMem::~CSharedMem()
{
UnmapViewOfFile(address_);
CloseHandle(mtx_);
}
void* CSharedMem::GetAddress() const
{
if(WaitForSingleObject(mtx_, INFINITE) != WAIT_OBJECT_0)
throw std::exception("Failed to obtain access to shared memory.");
return address_;
}
void CSharedMem::ReleaseAddress()
{
ReleaseMutex(mtx_);
}
bool CSharedMem::IsShared() const
{
return shared_;
}