[英]serial port connection - ReadFile always return 4 bytes read
我正在嘗試通過ReadFile進行讀取,但始終會使其讀取4個字節,不會雜念字符串有多長時間。
UART* uart = (UART*)lpParam;
char TempChar; //Temporary character used for reading
char SerialBuffer[256];//Buffer for storing Rxed Data
DWORD NoBytesRead;
int i = 0;
do
{
NoBytesRead = 0;
ReadFile(uart->connHandle, //Handle of the Serial port
&SerialBuffer, //Temporary character
sizeof(256),//Size of TempChar
&NoBytesRead, //Number of bytes read
NULL);
//SerialBuffer[i] = TempChar;// Store Tempchar into buffer
i++;
if (NoBytesRead > 0)
{
char* strMsg = (char*)malloc(sizeof(256 * sizeof(char)));
SerialBuffer[NoBytesRead] = '\0';
TRACE("read %d- %s\n", NoBytesRead,SerialBuffer);
strcpy_s(strMsg, 256,SerialBuffer);
ControllerPublishMsg(uart->controller, SerialBuffer);
}
SerialBuffer[0] = '\0';
如果我將字符串“ hh”發送到連接,則輸出為“ read 4- hh”。 該字符串的長度為2個字節,但NoBytesRead = 4。
謝謝。
sizeof(256)
默認為sizeof(int)
這是四個字節。 替換sizeof(256)
由256
。 還要將sizeof(256 * sizeof(char))
替換為(256 * sizeof(char))
。
考慮一下聲明
sizeof(256)
您通過的緩沖區大小。
該表達式的計算結果與
sizeof(int)
該值在您的平台上可能為4。 您需要將字面值256或更好的sizeof SerialBuffer
給ReadFile
。
而且您在malloc
參數中遇到了相同的錯誤。
如果沒有發送方的代碼,為什么您(認為自己)只發送2個字符時卻收到4個字符,這是看不到的。 如果ReadFile
返回4,則很可能接收到4個字符。 由於緩沖區大小參數混亂,因此它將不能接收超過4個字符 。
您正在濫用sizeof
。
調用ReadFile()
,您使用sizeof(256)
作為要讀取的字節數。 默認情況下,數字文字是int
,因此您實際上使用的是sizeof(int)
,它在編譯器上為4個字節。 擺脫sizeof
,僅使用256
:
ReadFile(uart->connHandle, //Handle of the Serial port
&SerialBuffer, //Temporary character
256,//Size of TempChar
&NoBytesRead, //Number of bytes read
NULL);
或sizeof(SerialBuffer)
的是,擺脫256
並改用sizeof(SerialBuffer)
,因為它是一個靜態數組,在編譯時已知其固定大小:
ReadFile(uart->connHandle, //Handle of the Serial port
&SerialBuffer, //Temporary character
sizeof(SerialBuffer),//Size of TempChar
&NoBytesRead, //Number of bytes read
NULL);
調用malloc()
時,您犯了類似的錯誤。 sizeof(char)
始終為1,因此您實際上是在再次調用sizeof(256)
。 同樣,您可以擺脫sizeof
,僅使用256
:
char* strMsg = (char*) malloc(256 * sizeof(char));
// or just: char* strMsg = (char*) malloc(256);
雖然,您實際上並沒有將strMsg
用於任何事情 (並且正在泄漏它),所以您應該完全擺脫它。
嘗試更多類似這樣的方法:
UART* uart = (UART*)lpParam;
char SerialBuffer[257];//Buffer for storing Rxed Data
DWORD NoBytesRead;
do
{
NoBytesRead = 0;
ReadFile(uart->connHandle, //Handle of the Serial port
SerialBuffer, //Temporary buffer
sizeof(SerialBuffer)-1,//Size of buffer minus null-terminator
&NoBytesRead, //Number of bytes read
NULL);
if (NoBytesRead > 0)
{
SerialBuffer[NoBytesRead] = '\0';
TRACE("read %u- %s\n", NoBytesRead, SerialBuffer);
ControllerPublishMsg(uart->controller, SerialBuffer);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.