How to load file font into RAM using C/C++ and SDL2?

感情迁移 提交于 2019-12-06 01:00:46

While freetype (which SDL_ttf uses) will not read font more than once (which it can't, since its API doesn't provide seek functionality), SDL_ttf will not close file/RWops until font closes. You can achieve what you've described via manually loading file into memory buffer and using that memory as RWops to feed data to SDL_ttf, e.g. (no error checking, no free, etc. - this is just an example):

    /* 'slurp' file (read entire file into memory buffer)
     * there are multiple ways to do so
     */
    SDL_RWops *file_rw = SDL_RWFromFile("font.ttf", "rb");
    Sint64 file_sz = file_rw->size(file_rw);
    void *membuf = malloc(file_sz);
    file_rw->read(file_rw, membuf, 1, file_sz);
    file_rw->close(file_rw);

    /* use memory buffer as RWops */
    SDL_RWops *mem_rw = SDL_RWFromConstMem(membuf, file_sz);
    TTF_Font *font = TTF_OpenFontRW(mem_rw, 1, font_size);

    /* free(membuf) when you're done with the font */

The secondary question about memcpy can be solved in the following way:

memcpy copies a file object, not its contents. In order to read from it:

Use fread function to read from FILE*: fread(ptr_File_copy, 1, var_file_size, ptr_load_file) instead of memcpy.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!