为什么 GetDefaultCommConfig 在 windows 10 上失败

How come GetDefaultCommConfig fails on windows 10

我使用下面的代码来验证串口名称在计算机上是否有效:

typedef std::pair<StrAsc const, bool> port_pair_type;
typedef std::list<port_pair_type> port_pairs_type;
port_pairs_type pairs;
StrBin config_buffer;
 config_buffer.fill(0,sizeof(COMMCONFIG));
while(!pairs.empty())
{
   port_pair_type pair(pairs.front());
   pairs.pop_front();
   if(!pair.second)
   {
      // we need to get the default configuration for the port.  This may
      // require some fudging on the buffer size.  That is why two calls
      // are being made.
      uint4 config_size = config_buffer.length();
      StrUni temp(pair.first);
      COMMCONFIG *config(reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable()));
      config->dwSize = sizeof(COMMCONFIG);
      rcd = GetDefaultCommConfigW(
         temp.c_str(), config, &config_size);
      if(!rcd && config_buffer.length() < config_size)
      {
         config_buffer.fill(0, config_size);
         config = reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable());
         config->dwSize = sizeof(COMMCONFIG);
         rcd = GetDefaultCommConfigW(
            temp.c_str(),
            reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable()),
                 &config_size);
      }

      // if the call succeeded, we can go ahead and look at the
      // configuration structure.
      if(rcd)
      {
         COMMCONFIG const *config = reinterpret_cast<COMMCONFIG const *>(
         config_buffer.getContents());
         if(config->dwProviderSubType == PST_RS232)
            port_names.push_back(pair.first);
      }
      else
      {
         OsException error("GetDefaultCommConfig Failed");
         trace("\"%s\"", error.what());
      }
   }
   else
      port_names.push_back(pair.first);
}

在windows10,当尝试确认使用usbser.sys的串口时,调用GetDefaultCommConfig()失败,GetLastError()返回的错误代码为87(参数无效) ).据我所知,usbser.sys 驱动程序已在 windows 10 上重写,我怀疑这是该驱动程序的问题。有没有其他人知道可能出了什么问题?

当您第二次调用 GetDefaultCommConfigW 时,您可能需要 config->dwSize 调整结构的新大小。例如:

config->dwSize = config_size;

这是 usbser.sys 中的一个错误,已通过 2016 年 1 月 27 日的 Windows 10 更新 KB3124262 修复。

Microsoft 员工解释说:

The COM port name in the HKLM\HARDWARE\DEVICEMAP\SERIALCOMM registry is not NULL terminated.

Related discussion on MSDN

由于 Windows 10 的更新政策,这个问题应该不会再出现了。