我必须连接两个 API,它们使用不同的结构来描述文件。第一个为我提供了 std::FILE*,第二个则期望属于 GIO 的 GFile* 或 GInputStream*。有没有一种简单的方法可以从我收到的原始文件指针创建任一对象?
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);
如果您想重用底层文件句柄,则需要针对特定平台。
fileno
与 g_unix_input_stream_new
结合使用
_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);
}
请记住,只要使用
file
,ginput
就应保持打开状态。