syoyo / tinyobjloader-c

Header only tiny wavefront .obj loader in pure C99
421 stars 60 forks source link

Windows version of map file #23

Open ekcury opened 5 years ago

ekcury commented 5 years ago

Hi!!! I was using the lib, on a windows platform I made a Map File version for windows, if you want to use it, feel free to use it. The only problem that you need to allocate space for the file and if this file is very large, read it in chunks The code has been tested

 char *g_pData=NULL;//Global data  free It later

static const char* mmap_fileWIN(size_t* len, const char* filename) 
{
    HANDLE hfile =
        CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    if(hfile == INVALID_HANDLE_VALUE)
    {
        printf("Erro:mmap_file   CreateFileA=INVALID_HANDLE_VALUE of %s \n",filename);
        printf("Could not open %s file, error %d\n", filename, GetLastError());
        return NULL;
    }

    DWORD dwsize = GetFileSize( hfile, NULL);
    if (dwsize == 0xFFFFFFFF) 
    {
        printf("Error:map_file Getfilesize 0xff\n");
        return NULL;
    }
    g_pData = (char*)malloc(dwsize);
        if(g_pData ==NULL)
                return NULL;

    HANDLE hFileMapping = CreateFileMapping(hfile, NULL, PAGE_READONLY, 0, 0, NULL);
    if(hFileMapping == INVALID_HANDLE_VALUE)
    {
        printf("Erro:mmap_file   CreateFileMapping=INVALID_HANDLE_of %s \n",filename);
        return NULL;
    }
    int iPos = 0;
    const unsigned int BlockSize = 128 * 1024;
    while(iPos < dwsize)//Read chunk of data
    {
        int iLeft = dwsize - iPos;
        int iBytesToRead = iLeft > BlockSize ? BlockSize: iLeft;

        void *rawBuffer = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, iPos, iBytesToRead);
        if(rawBuffer!=NULL)
        {
            memcpy(&g_pData[iPos], rawBuffer, iBytesToRead);
            UnmapViewOfFile(rawBuffer);
        }
        else
        {
            UnmapViewOfFile(rawBuffer);
            break;
        }
        iPos += iBytesToRead;
    }
    *len = dwsize;
    if(iPos!=0)
        return &g_pData[0];
    return NULL;
}
syoyo commented 5 years ago

Awesome!

Could you please send PR of this Map File version?

ekcury commented 5 years ago

Ok I'll try to adapt to the code, test to see if it has memory leaks etc.

ekcury commented 5 years ago

I send PR in my copy!