我必须连接两个 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);
最佳答案
如果您想重用底层文件句柄,则需要针对特定平台。
在 POSIX 上:
fileno
与g_unix_input_stream_new
结合在 Windows 上:
_get_osfhandle
与g_win32_input_stream_new
结合
例如这样:
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
就应该保持打开状态。
关于c++ - 从 std::FILE* 创建 GIO GFile 或 GInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63901592/