cwindowsmemorycircular-buffer

Windows ring buffer without copying


On Ring Buffer's Wikipedia entry, there's example code showing a hack for UNIX systems whereby the adjacent virtual memory to a piece of memory is mapped to the same phbysical memory, thus implementing a ring buffer without the need for any memcpy, etc. I was wondering if there's a way to so something similar in Windows?

Thanks, Fraser


Solution

  • I didn't really follow all the details of the example in wikipedia. With that in mind, you map memory in Windows using CreateFileMapping and MapViewOfFile, however MapViewOfFile does not allow you to specify a base address for the mapping. MapViewOfFileEx can be used to specify a base address so maybe you could use a similar technique.

    I don't have any way of telling if this would actually work:

    // determine valid buffer size
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    
    // note that the base address must be a multiple of the allocation granularity
    DWORD bufferSize=info.dwAllocationGranularity;
    
    HANDLE hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,
                 NULL,
                 PAGE_READWRITE,
                 0,
                 bufferSize*2,
                 L"Mapping");
    
    BYTE *pBuf = (BYTE*)MapViewOfFile(hMapFile,
                        FILE_MAP_ALL_ACCESS,
                        0,                   
                        0,                   
                        bufferSize);
    MapViewOfFileEx(hMapFile,
                        FILE_MAP_ALL_ACCESS,
                        0,                   
                        0,                   
                        bufferSize,
                        pBuf+bufferSize);