微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何改进在 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 举报,一经查实,本站将立刻删除。