[SDL] [OT] Resource file

Andre de Leiradella leiradella at bigfoot.com
Thu Feb 21 17:46:27 PST 2008


 >> This may be a bit of a n00b question, but when I looked
 >> up "mmapping", all the information I found seemed to indicate that
 >> it's just a UNIX/Linux thing.  Will this be cross-platform?
 >
 >That's a term based on the POSIX mmap() call, and AFAIK, Win32 has a
 >completely different native API. Try "memory mapped I/O" or something
 >like that.

A simple code (copy-on-write) to mmap/unmap a file within Windows is:

--------------------8<--------------------
typedef struct {
    HANDLE hFile;
    HANDLE hMap;
    void *contents;
} mmap_t;

int mmap(mmap_t *mm, const char *name, uint32_t offset, uint32_t size) {
    mm->hFile = CreateFile(
        name,    // pointer to name of the file
        GENERIC_READ | GENERIC_WRITE,    // access (read-write) mode
        0,    // share mode
        NULL,    // pointer to security attributes
        OPEN_EXISTING,    // how to create
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | 
FILE_FLAG_RANDOM_ACCESS,    // file attributes
        NULL    // handle to file with attributes to copy 
    );
    if (mm->hFile == INVALID_HANDLE_VALUE)
        return -1;
    mm->hMap = CreateFileMapping(
        mm->hFile,    // handle to file to map
        NULL,    // optional security attributes
        PAGE_WRITECOPY | SEC_COMMIT,    // protection for mapping object
        0,    // high-order 32 bits of object size 
        0,    // low-order 32 bits of object size 
        NULL    // name of file-mapping object
    );
    if (mm->hMap == NULL) {
        CloseHandle(hFile);
        return -1;
    }
    mm->contents = MapViewOfFile(
        mm->hMap,    // file-mapping object to map into address space 
        FILE_MAP_COPY,    // access mode
        0,    // high-order 32 bits of file offset
        offset,    // low-order 32 bits of file offset
        size    // number of bytes to map
    );
    if (mm->contents == NULL) {
        CloseHandle(mm->hMap);
        CloseHandle(mm->hFile);
        return -1;
    }
    return 0;
}

void munmap(mmap_t *mm) {
    UnmapViewOfFile(mm->contents);
    CloseHandle(mm->hMap);
    CloseHandle(mm->hFile);
}
--------------------8<--------------------

The contents of the file can be accessed through the contents member of 
the mmap_t structure.

Cheers,

Andre


More information about the SDL mailing list