简体   繁体   中英

boost deserialization gives me an input stream error

So, here's a simple bit of code I'm using to deserialize an std::map

std::map<std::string, std::string> func(std::string filepath) {
        map<std::string, std::string> filemap;
        // read file
        ifstream ifs(filepath, ios::in | ios::binary);
        if (!ifs.good()) {
            std::cout << "failed to read file" << std::endl;
            return filemap;
        }

        string content((istreambuf_iterator<char>(ifs)), (istreambuf_iterator<char>()));

        // deserialize
        stringstream ss;
        ss << content;
        std::cout << "content length: " << content.length() << std::endl;

        boost::archive::binary_iarchive ia(ss);
        try {
            ia >> filemap;
        }
        catch (const std::exception& e) {
            std::cout << e.what() << std::endl;
        }
        return filemap;
    }

Here's the thing that is making my heart palpitate. It runs fine in C++. ALWAYS . Again and again and again. I can deserialize the map, and do whatever I want with it. All good.

My C++ library, however, gets wrapped in CLI so that I can run it from a C# application (it has to be this way). From said C# application,

ia >> filemap;

produces an "input stream error". Not always, 19 out of 20 times I run it. I can't for the life of me understand why it behaves differently here. I'm close to pulling all my hair out.

I think the file reading part is fine. I can literally print out the contents of "content", and it looks fine.

Another funny thing that happens is, that after the first error is produced, if I wait for ~5-10 minutes, an "Debug Assertion Failed" error dialog appears, apparently from vector.h. It says "Expression: vector subscript out of range". I haven't worked out the source of that one yet, so I'm unsure if it's directly related or just a side-effect.

Binary archives are not platform independent. If you build using radically different compiler flags (c++-cli, eg) the layout will not be ccompatible.

If you need something more like that, use EOS Portable Archive .

Meanwhile:

I can literally print out the contents of "content", and it looks fine

It's binary data. How on earth can you see it "looks fine". It "looks fine" only if you can say it's bit-for-bit identical to something known-good (and you can prove that it's good). If you know that, you have confirmation that indeed the archive portability is the problem.

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