-5

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?

4

2 に答える 2

1

アドレス演算子を削除します。

bResult = ReadFile(hCom, inBuffer.GetBuffer(1), 1, &nBytesRead, NULL);

また: ReleaseBuffer への対応する呼び出しを忘れないでください。そして、そのキャラクターを追加するために

allData += inBuffer;

十分なはずです。

于 2011-06-30T09:11:10.017 に答える
0

まず、CStringは、プロジェクト用に選択したエンコーディングに従って動作します。プロジェクトがUnicode形式の場合、各文字は2バイト(WCHAR)で表されるCString文字で格納されます。ファイルとオブジェクトが同じエンコーディングを使用している場合は、正常に機能します。(また、最初にBOM文字を分析することでファイルエンコーディングを決定できます)

渡すバッファサイズは1です。それでもCStringオブジェクトを使用する場合は、GetFileSize()APIを呼び出してファイルの長さを渡すことにより、バッファに適切なサイズを渡してください。

バッファ割り当て方式を使用することをお勧めします。

お気に入り

char* pReadbuff = new char[sizeoffile];
ReadFile(..);
CString objStr = pReadbuff;
delete pReadbuff;
于 2011-06-30T10:20:10.377 に答える