Search code examples
c++strstream

How to initialise std::istringstream from const unsigned char* without cast or copy?


I have binary data in a byte sequence described by const unsigned char *p and size_t len. I want to be able to pass this data to a function that expects a std::istream *.

I think I should be able to do this without copying the data, unsafe casts or writing a new stream class. But so far I'm failing. Can anyone help?

Update

Thanks all for the comments. This would seem to be an unanswerable question because std::istream operates with char and conversion would at some point require at least an integer cast from unsigned char.

The pragmatic approach is to do this:

std::string s(reinterpret_cast<const char*>(p), len);
std::istringstream i(s);

and pass &i to the function expecting std::istream *.


Solution

  • Your answer is still copying.

    Have you considered something like this?

    const unsigned char *p;
    size_t len;
    
    std::istringstream str;
    str.rdbuf()->pubsetbuf(
        reinterpret_cast<char*>(const_cast<unsigned char*>(p)), len);