Search code examples
c++cfilegio

Creating a GIO GFile or GInputStream from std::FILE*


I have to connect two APIs, which use different structures to describe files. One provides me with a std::FILE* and the second one expects a GFile* or GInputStream* belonging to the GIO. Is there a straightforward way to create either object from the raw file pointer which I receive?

void my_function(std::FILE * file) {

GFile * gfile = some_creator_method(file);
//or alternatively
GInputStream * ginput = some_stream_creator_method(file);

//...
//pass the GFile to the other library interface
//either using:
interface_function(gfile);
//or using
interface_stream_function(ginput);
}

//The interface function signatures I want to pass the parameter to:

void interface_function(GFile * f);

void interface_stream_function(GInputStream * is);


Solution

  • If you want to re-use the underlying file handle, you will need to go platform-specific.

    For example like this:

    void my_method(FILE* file) {
    #ifdef _WIN32
        GInputStream* ginput = g_win32_input_stream_new(_get_osfhandle(file), false);
    #else
        GInputStream* ginput = g_unix_input_stream_new(fileno(file), false);
    #endif
    
        . . .
        . . .
    
        g_input_stream_close(ginput, nullptr, nullptr);
    }
    

    Keep in mind though that file should be kept open for as long as ginput is in use.