写串口函数如下:DWORD TController::WriteCom(HANDLE hcom,LPVOID OutBuffer,DWORD dwBufferLength)
{
bool bSuccess;
OVERLAPPED ol;
DWORD dwError,dwWriteCount;
memset(&ol,0,sizeof(ol));
if(ClearCommError(hCom, &dwError, NULL) && dwError > 0)
{PurgeComm(hCom, PURGE_TXABORT | PURGE_TXCLEAR);
}
bSuccess=WriteFile(hCom,OutBuffer,dwBufferLength,&dwWriteCount,&ol);
if(!bSuccess)
  {
   if(GetLastError()==ERROR_IO_PENDING)
     {
                      GetOverlappedResult(hCom, &ol, &dwWriteCount, true); //     }
   else
     {
            Application->MessageBox("写入串口时出现错误!", "错误", MB_OK +MB_ICONSTOP);
      return 0;
     }
  }return dwWriteCount;}但是,GetOverlappedResult的返回值是1啊,这说明成功返回了,为什么写入字节为0呢?这种情况只在连续2次调用writecom函数的时候出现,单次调用很少出现这样的问题,为什么呢?

解决方案 »

  1.   

    每次WriteCom之后加点延时试试,数据可能还没发出去。
      

  2.   

    Sleep(); 等待一下,让数据发送出去
      

  3.   

    OutBuffer,dwBufferLength
    调试看这两个内存
      

  4.   

    多谢大家!哈哈,这个错误大家都没看出来吧,不是OutBuffer,dwBufferLength 的问题,大家再看看,是什么地方出错拉?我已经找到了问题的原因,先不发出来,看谁先找到问题所在:)
      

  5.   

    bSuccess=WriteFile(hCom,OutBuffer,dwBufferLength,&dwWriteCount,&ol);
    if(!bSuccess)
      {
       if(GetLastError()==ERROR_IO_PENDING)
         {
                          GetOverlappedResult(hCom, &ol, &dwWriteCount, true); //-----------
    既然是ERROR_IO_PENDING状态,说明是写了dwWriteCount字节但是还没写进去,WriteFile执行完后dwWriteCount就是已写的字节数,GetOverlappedResult把dwWriteCount的值更新为已成功写入的字节数:ERROR_IO_PENDING状态的0。
      

  6.   

    呵呵,我来说出来吧,其实是ol结构里面有一个hevent没创建,所以。