【问题标题】:Creating a GIO GFile or GInputStream from std::FILE*从 std::FILE* 创建 GIO GFile 或 GInputStream
【发布时间】:2021-01-02 04:42:07
【问题描述】:

我必须连接两个 API,它们使用不同的结构来描述文件。一个为我提供std::FILE*,第二个期望GFile*GInputStream* 属于GIO。有没有一种直接的方法可以从我收到的原始文件指针创建任何一个对象?

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);

【问题讨论】:

    标签: c++ c file gio


    【解决方案1】:

    如果您想重用底层文件句柄,则需要特定于平台。

    例如这样:

    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);
    }
    

    请记住,只要 ginput 在使用中,file 就应该保持打开状态。

    【讨论】:

    • 如果我真的很挑剔,我不得不说这并不能完全回答这个问题,因为它没有提供GFile *。但尚不清楚 OP 是否真的想要GFile *,或者只是获得GInputStream * 的一种方式。
    • @KevinBoone GFile 不等同于FILEGFile 不代表打开的文件,仅代表文件元数据(名称、位置)。另一方面,FILE 表示 一个打开的文件,没有任何元数据(好吧,从技术上讲,在 Linux 上,有时可以从文件描述符中检索文件名,但我不推荐它)。
    • @geo -- 问题是GFile * 并不真正类似于FILE * -- GFile 更像是路径名而不是流。如果您有一个采用GInputStream * 的API,那么@rustyx 建议的方法应该可以工作,不是吗?
    • @geo GWin32InputStreamGUnixInputStream 都继承自 GInputStream,您可以在任何需要 GInputStream* 的地方提供它们。
    • 您可以从文件路径创建GFile。如果您不想将文件路径传递给您的函数,则需要以某种方式从FILE* 获取文件路径,这很重要。你可以得到一些灵感herehere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2022-10-13
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多