您好,我有一个关于从通信端口异步读取的问题。
我有一个函数,它应该从通信端口异步读取一个字节。该函数大约每 10 毫秒调用一次。我尝试同步执行,但缓冲区溢出,因为调用该函数的速度比它可以完成的速度快。现在我想异步实现它。但不明白它是如何工作的。
我的函数调用(每 10 毫秒调用一次):
// read one byte into receiveChar
bytesReceived = BSP_cliGetChar(&receiveChar);
函数体
int BSP_cliGetChar(char *rxBuffer)
{
DWORD numOfBytesRead;
OVERLAPPED readOverlapped;
HANDLE hEvent;
BOOL fOverlapped;
char str[255];
hEvent = CreateEvent(NULL, // default security attribute
TRUE, // manual-reset event
TRUE, // initial state = signaled
NULL); // unnamed event object
// set up overlapped structure fields
readOverlapped.Offset = 0;
readOverlapped.OffsetHigh = 0;
readOverlapped.hEvent = hEvent;
if (!ReadFile(hComm, rxBuffer, 1, &numOfBytesRead, &readOverlapped))
{
if (GetLastError() != ERROR_IO_PENDING)
{
// Some other error occurred while reading the file.
ExitProcess(0);
}
else
fOverlapped = TRUE;
}
else
{
// Operation has completed immediately.
fOverlapped = FALSE;
return (int) numOfBytesRead;
}
while(!HasOverlappedIoCompleted(&readOverlapped))
{
sprintf_s(str, "%d", &numOfBytesRead);
OutputDebugString(str);
}
}
现在我想要的是从 com 端口读取一个字节。如果返回 ERROR_IO_PENDING,调用函数应该继续。只有接收到一个字节,BSP_cliGetChar 函数才应该返回。问题是,该方法停留在 while 循环中,而不是继续调用过程。
任何有想法如何解决这个问题的人?
谢谢您的帮助。