2014-02-27 246 views
1

multi_index容器我有这样的结构:在共享内存

struct myData 
{ 
    unsigned long id; 
    int age; 
    int phone; 

    myData(){}; 
    myData(unsigned long id_, int age_, int phone_) 
     :id(id_),age(age_),phone(phone_){} 
    ~myData(){}; 
}; 

这multi_index容器:

typedef multi_index_container< 
    myData, 
     indexed_by<  
      random_access<>, // keep insertion order 
      ordered_non_unique< member<myData, int, &myData::age> > 
     > 
> myDataContainerType; 

typedef myDataContainerType::nth_index<1>::type myDataContainerType_by_Id; 
myDataContainerType myDataContainer; 

这个插入功能:

bool insert(unsigned long id, int age, int phone) { 

    myDataContainerType::iterator it; 
    bool success; 
    boost::mutex::scoped_lock scoped_lock(mutex); // LOCK 
    std::pair<myDataContainerType::iterator, bool> result = myDataContainer.push_back(myData(id, age, phone)); 
    it = result.first; 
    success = result.second; 
    if (success) 
     return true; 
    else 
     return false; 
} 

,所以我想提出这个muti_index容器到shared memory以使其可以从其他应用程序访问。我看到thisthat例子,但我不明白,allocator东西都(为什么我需要一个char分配?做什么样的分配的,我需要在这里等使用...)

有人可以给我解释一下如何把这个容器共享内存?

感谢的确...

编辑:

好吧,我将我的这个代码:

myDataContainerType *myDataContainer ; 

void createInSharedMemory() 
{ 
    managed_shared_memory segment(create_only,"mySharedMemory", 65536); 

    myDataContainer = segment.construct<myDataContainerType> 
     ("MyContainer")   //Container's name in shared memory 
     (myDataContainerType::ctor_args_list() 
     , segment.get_allocator<myData>()); //Ctor parameters 

} 

,并尝试插入数据这样的:

bool insert(unsigned long id, int age, int phone) { 

    myDataContainerType::iterator it; 
    bool success; 
    boost::mutex::scoped_lock scoped_lock(mutex); // LOCK 
    std::pair<myDataContainerType::iterator, bool> result = myDataContainer->insert(MyData(id, age, phone));  

    it = result.first; 
    success = result.second; 
    if (success) 
     return true; 
    else 
     return false; 
} 

但我在插入行中得到这个错误:(在offset_ptr .hpp)

Unhandled exception at 0x000000013fa84748 in LDB_v1.exe: 0xC0000005: Access violation reading location 0x0000000001d200d0. 

任何想法请???

+0

你需要一个char分配器来分配'char'对象的连续区域。你知道,当你分配字符串时,你会怎么做? (从样本中很清楚)。请告诉我们实际的代码和你卡住的地方。目前看起来你期待着我们做你的工作? – sehe

+0

问题是我不明白,如果我有一个分配器,如在示例中的分配器,但因为我没有字符串,我想我也不需要该分配器。所以我认为我必须像这个例子一样来建立它。 http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.additional_containers.multi_index。我怎样才能从其他应用程序到达容器?对不起,我不希望你做这项工作,但我不知道该怎么做?这是我第一次使用共享内存。 – user2955554

回答

0

您是否在拨打segment.construct后检查myDataContainer是否为非空?也许你需要使用segment.find_or_construct

+0

感谢您的回答。我只是想,如果我从managed_shared_memory开始......在函数外面,它没有错误地工作。我认为这一定是全球性的。顺便说一下,其他应用程序将如何到达我的容器? – user2955554

+0

要访问同一个容器,分别为内存管理器和容器使用相同的名称“mySharedMemory”和“MyContainer”。 –

+0

我明白了,但是我的语法有问题。我必须从阅读器应用程序到达容器,并从它执行搜索和检索数据。你有这样的代码示例吗?非常感谢你。 – user2955554