如何改进在 Android 上的 C++ 中获取 FileDescriptor

问题描述

我在我的 Android 应用程序的本机部分中有这个功能,到目前为止可以正常工作:

bool Converter::doConversion(const std::string &fullPath,const std::string &name) {
    
    AMediaExtractor *extractor = AMediaExtractor_new();
    if (extractor == nullptr) {
        LOGE("Could not obtain AMediaExtractor");
        return false;
    }

    FILE* myFile = fopen(fullPath.c_str(),"r");
    std::ifstream stream;
    stream.open(fullPath,std::ifstream::in | std::ifstream::binary);

    if (!stream.is_open() || myFile == nullptr) {
        LOGE("File opening Failed! %s",fullPath.c_str());
        return false;
    }
    stream.seekg(0,std::ios::end);
    int fd = fileno(myFile);
    long size = stream.tellg();
    stream.close();

    media_status_t amresult = AMediaExtractor_setDataSourceFd(extractor,fd,size);

    // here is where I do stuff with my extractor. This code is omitted as it works fine and is unrelated to the question

    fclose(myFile); // close file after conversion is done to avoid memory leaks
}

媒体提取器还有一个 setDataSource() 函数,我可以在其中输入文件名,但由于 Android Q 和它的范围存储更改,这将不再起作用,因为它看起来像像错误一样见 this question and its answer

因此,我需要向它提供一个文件描述符,该描述符是从我的 File*获取的,以及我通过在 tellg()调用 ifstream 获得的文件大小。>

显然,我不是 C++ 专家,因为我确信这可以比基本上打开文件两次以获取有关它的一些信息更好的方式来完成,然后第三次打开文件需要这些信息时间。此外,我不确定我应该在这里注意哪些可能的错误

那么我该如何改进这个功能并使其更高效?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)