简体   繁体   中英

How to get std::basic_istream from AAssetManager?

I am using NDK and I need to read resource media file. So, as far as I understand in order to access to resources I need to use AAssetManager , and eventually I need to get std::basic_istream to work with it.

So, question is, how to get std::basic_istream from AAssetManager ?

The answer is actually very different whether you have a compressed asset (eg text) or uncompressed (by default, Jpeg images and mp3 are stored by the packer). For these uncompressed assets, you can get the file descriptor with AAsset_openFileDescriptor() , and then follow the ways of How to construct a c++ fstream from a POSIX file descriptor? . For compressed assets, you may look for a (potentially API-level-dependent) hack that will let you get the file descriptor (or file path) to the transient file that the OS opens for you when it unpacks your asset.

You can adapt this example to work with the "buffer" mode of AAssetManager .

This will read the entire asset into memory, though. You could make an implementation that works more like std::fstream by reading chunks into a memory buffer, but that is significantly more complex.

Note: I only test-compiled the code below.

class asset_streambuf : public std::streambuf {
    public:
        asset_streambuf(AAsset * the_asset)
            : the_asset_(the_asset) {
                char * begin = (char *)AAsset_getBuffer(the_asset);
                char * end = begin + AAsset_getLength64(the_asset);
                setg(begin, begin, end);
            }
        ~asset_streambuf() {
            AAsset_close(the_asset_);
        }
    private:
        AAsset * the_asset_;
};

Usage:

AAsset * asset = AAssetManager_open(mgr, "some_asset.bin", AASSET_MODE_BUFFER);
asset_streambuf sb(asset);
std::istream is(&sb);

EDIT: Found a shorter way based on this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM