【发布时间】:2015-07-17 18:25:59
【问题描述】:
我使用以下代码来验证计算机上的串口名称是否有效:
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);
}
在 Windows 10 上,当尝试确认使用 usbser.sys 的串行端口时,对 GetDefaultCommConfig() 的调用失败,GetLastError() 返回的错误代码为 87(无效参数)。据我所知,usbser.sys 驱动程序已在 Windows 10 上重写,我怀疑这是该驱动程序的问题。有没有其他人知道可能出了什么问题?
【问题讨论】:
-
每次使用
reinterpret_cast都会引发危险信号。仔细检查以确保您发送的COMMCONFIG数据确实有效。将您的代码简化为您明确初始化COMMCONFIG的实例,并使用 known 值来工作。 -
@CaptainObvlious COMMCONFIG 是一个可变长度的结构,根据驱动程序的不同,它必须被放大以保存额外的信息。我在 StrBin(二进制缓冲区类)中执行此操作以管理此分配。
-
@CaptainObvlious 我要进一步指出,此代码适用于除使用 usbser.sys 驱动程序的端口之外的所有其他端口类型。它也适用于较旧的操作系统。
-
设置的端口号是多少?请记住,带有“\\\\.\\COM20”之类的端口描述符将不起作用。另请参阅此帖子:stackoverflow.com/questions/13191777/…
标签: c++ winapi serial-port