我用API函数写的串口通信,在发送字符时,WriteFile(hCom,&c,length,&length,&m_osWrite);函数总是使用错误,错误号为87,查csdn,这个错误是The parameter is incorrect。请问是怎么回事,具体是哪个参数有问题?

解决方案 »

  1.   

    WriteFile(hCom,&c,length,&length,&m_osWrite);
    你的两个length有错误。
    函数原型:
    BOOL WriteFile(
      HANDLE hFile,                    // handle to file
      LPCVOID lpBuffer,                // data buffer
      DWORD nNumberOfBytesToWrite,     // number of bytes to write
      LPDWORD lpNumberOfBytesWritten,  // number of bytes written
      LPOVERLAPPED lpOverlapped        // overlapped buffer
    );
    请注意看以下对你传入length参数的说明:
    nNumberOfBytesToWrite 
    [in] Specifies the number of bytes to write to the file. 
    A value of zero specifies a null write operation. A null write operation does not write any bytes but does cause the time stamp to change. Named pipe write operations across a network are limited to 65,535 bytes. lpNumberOfBytesWritten 
    [out] Pointer to the variable that receives the number of bytes written. WriteFile sets this value to zero before doing any work or error checking. 
    =====
    lpNumberOfBytesWritten 是个输出参数,用来返回数据的。
    WriteFile sets this value to zero before doing any work or error checking. 
    就是说,这个函数在做所有事情之前,首先干的工作是将它设置为0。因为你传入和输出用的都是length这一个变量,那么由于这个函数首先将length设置为0了,那么你传入的length也就是0了,自然会报告参数错误了。你写入0个数据自然有问题了。
      

  2.   

    BOOL WriteFile(
      HANDLE hFile,                    // handle to file
      LPCVOID lpBuffer,                // data buffer
      DWORD nNumberOfBytesToWrite,     // number of bytes to write
      LPDWORD lpNumberOfBytesWritten,  // number of bytes written
      LPOVERLAPPED lpOverlapped        // overlapped buffer
    );
      

  3.   

    BOOL WriteFile(
      HANDLE hFile,                    // handle to file
      LPCVOID lpBuffer,                // data buffer
      DWORD nNumberOfBytesToWrite,     // number of bytes to write
      LPDWORD lpNumberOfBytesWritten,  // number of bytes written
      LPOVERLAPPED lpOverlapped        // overlapped buffer
    );容易出错的地方:
    lpBuffer不是常量,lpOverlapped不匹配,
    第三和第四个参数不能用同一个,
      

  4.   

    第三个参数和第四个参数我改为不一样的还是会出问题,返回的错误号还是87。我的第二个参数类型是char,不知道是不是这儿出了问题
      

  5.   

    BOOL fWriteStat;
    unsigned long aa;
    OVERLAPPED npTTYInfo;
    npTTYInfo.Offset = 0;
    npTTYInfo.OffsetHigh = 0;
    npTTYInfo.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
    if(npTTYInfo.hEvent == NULL)
    return ;
    char szBuffer[256]="#0199oo\r";
    fWriteStat = WriteFile(hCom, szBuffer,10,&aa, &npTTYInfo); //写数据
      

  6.   

    发送没问题了,但是WriteFile函数返回还是0,最后的错误号是997:Overlapped I/O operation is in progress。。不过好歹可以发送了,有兴趣的再讨论一下这是怎么回事,我看了其他的很多串口的程序,虽然都能发送数据,但是WriteFile函数返回都是0,错误号都是997。
      

  7.   

    你有异步(重叠)方式发送数据,函数不等执行完就Return ,也就是说,无论WriteFile()是否成功都会立即返回,这样就不用再串口操作的时候堵塞了。
    看MSDN,CreateFile,WriteFile关于异步方式的说明