开发者

How to use mmap to point to STL type?

I have a mmap typecast to a char pointer

char *ptr;

ptr = (char *)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

This was my earlier code. But now I want to use a map ins开发者_开发知识库tead of char * as the requirements changed.

Now, my map is declared as map < int, string > i_s_map;

How do I change my mmap call to point to the map?


You don't want to store STL containers in shared memory, at least not share them. The reason is that they rely heavily on heap allocation, so out-of-the-box std::map will hold pointers from virtual address space of a different process.

Take a look at boost::interprocess for a way to deal with this situation in C++.


If you want to create a map object in the memory returned by mmap use placement new.

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

That will create the map object itself in the memory. In order to get the elements inside the map into the memory, you will need to create a custom allocator to keep the data in the memory. You can use the boost interprocess library for some allocators which work inside shared memory.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜