gcc std::istream 'error: invalid cast from type ‘std::streamsize’ to type ‘std::streamsize’'
Alright, so here is a really weird one. I am reading raw data into a buffer, nothing fancy, my code went like so:
typedef unsigned char Byte;
/* ... */
static Byte Se开发者_JAVA百科rializeBuffer[2048];
/* ... */
std::streamsize readInBuffer =
data.read((char*)SerializeBuffer, sizeof(SerializeBuffer));
But I would keep getting the compile error message 'error: invalid cast from type ‘void *’ to type ‘std::streamsize’'
, No idea why the compiler thought that sizeof was a void pointer. Well I tried casting it in several ways, but the same error kept happening. I ended up with this:
std::streamsize dummy = sizeof(SerializeBuffer);
std::streamsize readInBuffer =
data.read((char*)SerializeBuffer, reinterpret_cast<std::streamsize>(dummy));
Which pops up the following: error: invalid cast from type ‘std::streamsize’ to type ‘std::streamsize’
I am at a complete loss. Any other Ideas?
Compiler: gcc 4.4.5
OS: Linux 2.6.35edit: Same thing on Visual Studio 2010
If data
is an istream
, keep in mind that the member read
returns a reference to data
(the stream itself), not the number of characters read.
The void *
stuff is probably because the compiler, to assign it to the std::streamsize
member, tries to use the implicit conversion to void *
(the one that is used when you do if(data) ...
), but still void *
is not a good match for std::streamsize
.
By the way, the information about the number of characters read can be obtained, after the call to read
, using the gcount
method.
You should check the documentation. Read returns a reference to the stream. So what's happening is:
- You call read, which returns an istream&.
- You try to assign that istream to a std::streamsize.
- Since the compiler does not find a suitable way to do this, it tryes to assign the result of the stream's operator void* to your std::streamsize.
- Since you can't assign these types, an error is produced.
It must be the std::streamsize readInBuffer = data.read(...
part. read
doesn't return size, but the stream itself.
If you want to know how many bytes were read use readsome()
not read()
精彩评论