Created
October 31, 2021 12:22
-
-
Save jweinst1/a3add979713e62f514fbd880168c3a17 to your computer and use it in GitHub Desktop.
C++ way of doing placement new on an mmap buffer
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
#include <cstdlib> | |
#include <cstdio> | |
#include <cstdint> | |
#include <sys/mman.h> | |
#include <new> | |
#include <atomic> | |
template<class T> | |
struct memory_ptr { | |
std::atomic<bool> in_use; | |
uint16_t tid; | |
T obj; | |
memory_ptr(): in_use(false), tid(0) {} | |
}; | |
int main(void) { | |
void* ptrmap = ::mmap( NULL, 50, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); | |
if (ptrmap == MAP_FAILED) { | |
std::fprintf(stderr, "%s\n", "Got map failed!!"); | |
std::exit(1); | |
} | |
memory_ptr<int>* obj = new (ptrmap) memory_ptr<int>(); | |
std::printf("%zu\n", sizeof(memory_ptr<int>)); | |
obj->tid = 3; | |
/* | |
char* writer = (char*)ptrmap; | |
writer[0] = 'e'; | |
writer[1] = 'w'; | |
writer[2] = '\0'; | |
std::puts(writer);*/ | |
::munmap(ptrmap, 50); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment