0

我现在正在使用 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");
 }
4

1 回答 1

2

这一行:

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

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

它类似于:

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

关于你的第二个问题,如果没有看到更多代码,这有点难以判断,但看起来它只是为读入的每个数据块增加一个“总大小”变量(加上sb.sputn应该做的任何事情)。

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

于 2012-05-11T06:55:13.690 回答