繁体   English   中英

串行端口连接-ReadFile始终返回读取的4个字节

[英]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 SerialBufferReadFile

而且您在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM