Search code examples
c++windowsmmap

analogy to mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); in windows


I'm trying to port some linux C++ to windows and have stuck at a line like this

void* ptr = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

which as I found out is a way to dynamically allocate some memory as file descriptor is -1.

How do I do this in windows? I couldn't find anything in documentation that MapViewOfFile could be used without file handler.


Solution

  • MapViewOfFile does not take file handle, it takes file mapping handle. To allocate chunk of memory you can create an anonymous file mapping like this:

    ::DWORD const bytes_count_to_map{4u * 1024u * 1024u};
    auto const h_mapping
    {
        ::CreateFileMappingW
        (
            INVALID_HANDLE_VALUE        // not binded to actual file
        ,   nullptr                     // default security
        ,   PAGE_READWRITE | SEC_COMMIT // access flags
        ,   0u                          // map high
        ,   bytes_count_to_map          // map low
        ,   nullptr                     // no name
        )
    };
    if(NULL == h_mapping)
    {
        auto const last_error{::GetLastError()};
        // TODO deal with error...
        exit(-1);
    }
    auto const p_view
    {
        ::MapViewOfFile
        (
            h_mapping                      // mapping handle
        ,   FILE_MAP_READ | FILE_MAP_WRITE // map flags
        ,   0                              // offset high
        ,   0                              // offset low
        ,   bytes_count_to_map             // size
        )
    };
    if(nullptr == p_view)
    {
        auto const last_error{::GetLastError()};
        // TODO deal with error...
        exit(-2);
    }
    if(FALSE == ::UnmapViewOfFile(p_view))
    {
        auto const last_error{::GetLastError()};
        // TODO deal with error...
        exit(-3);
    }
    if(FALSE == ::CloseHandle(h_mapping))
    {
        auto const last_error{::GetLastError()};
        // TODO deal with error...
        exit(-4);
    }