当缓冲区为 CString 时 ReadFile 的奇怪行为
我继承了使用 ReadFile
Windows API 方法从循环中的并行端口读取单个字节的代码。
该代码将 CString
实例作为缓冲区参数传递,并将 1 作为要读取的字节数,如下所示:
CString inBuffer = "";
bResult = ReadFile(hCom, inBuffer.GetBuffer(1), 1, &nBytesRead, NULL);
allData += inBuffer.GetBuffer(1);
它使用此代码运行了很长时间,但有时会导致奇怪的问题,例如从“AV01000”的机器被读取为“AkVk0k1k0k0k0” - 不知何故,在读取每个字符后添加了一些随机字符。
我花了很长时间才弄清楚这种行为的根源,并将代码更改为:
char buffer = '\0';
bResult = ReadFile(hCom, &buffer, 1, &nBytesRead, NULL);
allData += buffer;
它完美地工作,读取机器发送的确切数据。
这是 CString
内部代码中的某种缓冲区溢出吗?如果不是,什么可以解释这种奇怪的行为?
I have inherited code using ReadFile
Windows API method to read single byte from parallel port in a loop.
The code passed CString
instance as the buffer argument, and 1 as the number of bytes to read, something like this:
CString inBuffer = "";
bResult = ReadFile(hCom, inBuffer.GetBuffer(1), 1, &nBytesRead, NULL);
allData += inBuffer.GetBuffer(1);
It worked for long time with this code, but sometimes caused weird problems for example input sent from the machine as "AV01000" was read as "AkVk0k1k0k0k0" - somehow some random character was added after each character read.
Took me long time to figure the source of this behavior, and after changing the code to:
char buffer = '\0';
bResult = ReadFile(hCom, &buffer, 1, &nBytesRead, NULL);
allData += buffer;
It worked flawlessly, reading the exact data sent by the machine.
Is this some kind of buffer overflow in the internal code of CString
? If not, what might explain this weird behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
删除地址运算符:
另外:不要忘记对 ReleaseBuffer 的匹配调用。添加该字符
应该就足够了。
Remove the address operator:
Also: Don't forget the matching call to ReleaseBuffer. And for adding that character
should be sufficient.
首先,CString 根据您为项目选择的编码进行操作。如果您的项目是Unicode格式,则每个字符都存储在以两个字节表示的CString字符(WCHAR)中。如果文件和对象具有相同的编码,它将正常工作。 (您也可以通过分析开头的 BOM 字符来确定文件编码)
您传递的缓冲区大小是 1。如果您仍然想使用 CString 对象,请通过调用传递文件的长度来传递正确的缓冲区大小获取文件大小() API。
我建议您使用缓冲区分配方法。
喜欢
First thing is that, CString acts according to the encoding you're chosen for the project. If your project is Unicode format, each character is stored in the CString character represented in two bytes(WCHAR). If the file and object are having same encoding, it will work fine. (Also you can determine the file encoding by analyzing BOM character in the beginning)
The buffer size you're passing is 1. If you still want to use the CString object, please pass the proper size for the buffer by passing file's length by calling GetFileSize() API.
I suggest you to use the buffer allocated method.
like