开发者

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

开发者 https://www.devze.com 2023-03-21 03:24 出处:网络
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 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 shou开发者_JS百科ld 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 *.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消