我試圖在共享內存段上存儲一個std :: map。但我無法恢復地圖。Cast void * to 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_;
}
你的代碼不可能工作。問題比看起來更復雜。閱讀STL分配器和新的放置位置。你需要兩個概念。你也必須在固定的地址分配你的共享內存段。 –