代码之家  ›  专栏  ›  技术社区  ›  srikanta

如何使用mmap指向stl类型?

  •  1
  • srikanta  · 技术社区  · 15 年前

    我有一个mmap类型转换成char指针

    CHAR*PTR;

    ptr=(char*)mmap(0,文件大小,prot_read_prot_write,map_shared,fd,0);

    这是我以前的代码。但是现在,随着需求的变化,我想使用一个映射而不是char*。

    现在,我的地图被宣布为 map<int,string>i_s_map;

    如何更改mmap呼叫以指向地图?

    2 回复  |  直到 15 年前
        1
  •  6
  •   Nikolai Fetissov    15 年前

    您不想在共享内存中存储STL容器,至少不想共享它们。原因是它们严重依赖堆分配,因此是开箱即用的 std::map 将保留来自不同进程的虚拟地址空间的指针。

    看一看 boost::interprocess 为解决C++中的这种情况提供了一种方法。

        2
  •  2
  •   Zanson    15 年前

    如果要在mmap返回的内存中创建映射对象,请使用placement new。

    map<int,string> *i_s_map = new(ptr) map<int,string>();
    

    这将在内存中创建映射对象本身。为了将映射中的元素放入内存,您需要创建一个自定义分配器来将数据保存在内存中。对于在共享内存中工作的一些分配器,可以使用boost进程间库。

    http://www.boost.org/doc/libs/1_42_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.allocator_introduction