Created
May 10, 2018 22:42
-
-
Save d33tah/2cc5fae986c517152fa15e03150f8698 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//My improved version of code from this blog post: | |
//http://voices.canonical.com/jussi.pakkanen/2013/09/14/serialising-any-c-data-structure-to-disk-with-20-lines-of-code/ | |
#include <map> | |
#include <string> | |
#include <sys/mman.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
void *mmap_start = (void*)0x7f15b0910000; | |
size_t offset = 0; | |
void *mapping; | |
void * operator new(std::size_t num) | |
{ | |
printf("Trying to allocate %ld bytes.\n", num); | |
long returnvalue = (long)mmap_start + offset; | |
offset += (num + 8) - (num % 8); | |
return (void*)returnvalue; | |
} | |
void operator delete(void * p) throw() {} | |
void read() { | |
auto *map = reinterpret_cast<std::map<std::string, | |
std::string> *>(mmap_start); | |
std::string key("key"); | |
printf("Sizeof map: %ld.\n", (long)map->size()); | |
printf("Value of 'key': %s\n", (*map)[key].c_str()); | |
} | |
void write() { | |
auto map = new std::map<std::string, std::string>(); | |
std::string key("key"); | |
std::string value("value2"); | |
(*map)[key] = value; | |
printf("Sizeof map: %ld.\n", (long)map->size()); | |
printf("Value of 'key': %s\n", (*map)[key].c_str()); | |
} | |
int main(int argc, char **argv) { | |
int fd = open("backingstore.dat", O_RDWR); | |
if(fd < 1) { | |
printf("Open failed.\n"); | |
return 1; | |
} | |
mapping = mmap(mmap_start, 10*1024*1024, | |
PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); | |
if(mapping == MAP_FAILED) { | |
printf("MMap failed.\n"); | |
return 1; | |
} | |
write(); | |
read(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment