gcc std::istream '错误:从类型 ‘std::streamsize’ 进行无效转换输入“std::streamsize”
好吧,这是一个非常奇怪的情况。我正在将原始数据读入缓冲区,没什么花哨的,我的代码是这样的:
typedef unsigned char Byte;
/* ... */
static Byte SerializeBuffer[2048];
/* ... */
std::streamsize readInBuffer =
data.read((char*)SerializeBuffer, sizeof(SerializeBuffer));
但我会不断收到编译错误消息 'error: invalidcast from type 'void *' to type 'std::streamsize''
,不知道为什么编译器认为 sizeof 是一个 void 指针。好吧,我尝试用多种方式进行转换,但同样的错误不断发生。我最终得到了这个:
std::streamsize dummy = sizeof(SerializeBuffer);
std::streamsize readInBuffer =
data.read((char*)SerializeBuffer, reinterpret_cast<std::streamsize>(dummy));
弹出以下内容: error: invalidcast from type 'std::streamsize' to type 'std::streamsize'
我完全不知所措。还有其他想法吗?
编译器:gcc 4.4.5
操作系统:Linux 2.6.35
编辑: Visual Studio 2010 上也是如此
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 SerializeBuffer[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.35
edit:
Same thing on Visual Studio 2010
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
data
是一个istream
,请记住成员read
返回对data
的引用(流本身),而不是读取的字符数。void *
内容可能是因为编译器将其分配给std::streamsize
成员,尝试使用隐式转换为void *
> (当您执行if(data) ...
时使用的那个),但仍然void *
与std::streamsize 不太匹配
。顺便说一句,在调用
read
之后,可以使用gcount
方法。If
data
is anistream
, keep in mind that the memberread
returns a reference todata
(the stream itself), not the number of characters read.The
void *
stuff is probably because the compiler, to assign it to thestd::streamsize
member, tries to use the implicit conversion tovoid *
(the one that is used when you doif(data) ...
), but stillvoid *
is not a good match forstd::streamsize
.By the way, the information about the number of characters read can be obtained, after the call to
read
, using thegcount
method.您应该查看文档。 Read 返回对流的引用。所以发生的事情是:
You should check the documentation. Read returns a reference to the stream. So what's happening is:
它必须是
std::streamsize readInBuffer = data.read(...
部分。read
不返回大小,而是返回流本身。It must be the
std::streamsize readInBuffer = data.read(...
part.read
doesn't return size, but the stream itself.如果您想知道读取了多少字节,请使用
readsome()
而不是read()
If you want to know how many bytes were read use
readsome()
notread()