You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Windows API在C++中读取指定串口的未处理输入/输出缓冲区?

在Windows API中获取串口缓冲区未读/未发送字节数

你需要的功能可以通过ClearCommError()函数实现,它是Windows API中专门用于获取串口状态(包括缓冲区字节数)的函数,不会清空缓冲区,完全匹配你提到的pyserial库in_waiting和out_waiting的需求。

核心用法说明

ClearCommError()不仅能返回串口通信错误,还会通过COMSTAT结构体输出当前串口的缓冲区状态:

  • COMSTAT.cbInQue:输入缓冲区中未被读取的字节数(对应in_waiting)
  • COMSTAT.cbOutQue:输出缓冲区中尚未发送的字节数(对应out_waiting)

示例代码

#include <windows.h>
#include <iostream>

int main() {
    // 打开串口(替换为你实际要操作的串口,如COM1、COM3等)
    HANDLE hSerial = CreateFile(
        L"COM3",
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    if (hSerial == INVALID_HANDLE_VALUE) {
        std::cerr << "串口打开失败,错误码: " << GetLastError() << std::endl;
        return 1;
    }

    DWORD errorFlags;
    COMSTAT commStatus;

    // 获取串口状态与缓冲区信息
    if (ClearCommError(hSerial, &errorFlags, &commStatus)) {
        std::cout << "输入缓冲区未读字节数: " << commStatus.cbInQue << "\n";
        std::cout << "输出缓冲区未发送字节数: " << commStatus.cbOutQue << "\n";
    } else {
        std::cerr << "获取串口状态失败,错误码: " << GetLastError() << std::endl;
    }

    // 关闭串口句柄
    CloseHandle(hSerial);
    return 0;
}

注意事项

  • ClearCommError()会清除当前的串口错误标志,但不会修改输入/输出缓冲区中的数据,不会影响后续的ReadFile或WriteFile操作。
  • 调用前确保串口句柄是有效的(已成功打开串口)。

内容的提问来源于stack exchange,提问作者Mqx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 16:20:10