c - 解释DWORD在串行通信中的使用

标签 c serial-port readfile

我现在正在研究用C语言与win32进行串行通信。从串口读取数据如下。

DWORD dwEventMask;
DWORD dwSize;

if(!SetCommMask(hSerial, EV_RXCHAR)){
    //Error handling
    printf("Error Setting Comm Mask \n");
}

if(WaitCommEvent(hSerial, &dwEventMask, NULL))
{
    unsigned char szBuf[1024];
    DWORD dwIncommingReadSize;

    do
    {
        if(ReadFile(hSerial, &szBuf, 1, &dwIncommingReadSize, NULL) != 0) {
            //Handle Error Condition
        }

        if(dwIncommingReadSize > 0)
        {
            dwSize += dwIncommingReadSize;
            sb.sputn(&szBuf, dwIncommingReadSize);
            printf("Reading from port \n");
        }
        else{
        //Handle Error Condition
        }
        printf("Reading data from port \n");
    } while(dwIncommingReadSize > 0);
}
else
{
        //Handle Error Condition
}

他们使用 DWORD dwIncommingReadSize 作为 while 条件 (while(dwIncommingReadSize > 0);。

请解释一下如何满足这个条件。对此看不到任何修改。

请再次解释以下部分。

if(dwIncommingReadSize > 0)
{
    dwSize += dwIncommingReadSize;
    sb.sputn(&szBuf, dwIncommingReadSize);
    printf("Reading from port \n");
 }

最佳答案

这一行:

if(ReadFile(hSerial, &szBuf, 1, &dwIncommingReadSize, NULL)

dwIncommingReadSize地址(无论拼写可能多么糟糕)传递给函数,以便它可以将其更改为所需的任何内容。

它类似于:

void fn (int *x) { *x = 42; }
:
int xyzzy = 1;
fn (&xyzzy);
// Here, xyzzy is now 42.
<小时/>

就你的第二个问题而言,如果没有看到更多代码,就很难判断,但看起来它只是为读入的每个数据 block 增加了一个“总大小”变量(加上任何 sb .sputn 应该做)。

这是典型的情况,一次读取可能无法获得您想要的所有数据 - 您只需存储您获得的数据,然后返回获取更多数据。

关于c - 解释DWORD在串行通信中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546784/

相关文章:

c# - 使用 LINQ 查找串行设备列表

c++ - Windows XP 上的 ReadFile 函数失败,错误代码为 2

c - 为什么过早访问 ReadFileEx 的输入缓冲区会导致数据损坏?

c++ - ReadFile() 说失败,但错误代码是 ERROR_SUCCESS

c - LLVM——链接问题

c# - 连续接收来自秤的数据

c - 如果文件名在 DOS 8.3 风格中相同,则 MoveFile 和 MoveFileEx 工作异常

c# - asp C# 如何在同一个程序中通过串口读取和发送数据

c - c中以下代码有什么问题

Python-C api并发问题