我使用以下代码行分配一个com端口:
const wchar_t* mccommport = L"COM5";
然后我可以调用mccommport,如果我需要使用它。这很完美。但是我想现在从标签中提取要使用的COM端口。我怎样才能做到这一点?换句话说:
QString mccommport_string = ui->label_commport->text(); //Value here is COM5
const wchar_t* mccommport = mccommport_string ; //????? obviously this doesn't work.
我如何完成上述工作?
我尝试了以下但没有成功:
wchar_t array[5];
QString mccommport_string = "COM5"
mccommport_string.toWCharArray(array);
const wchar_t* mccommport = array;
const wchar_t* mccommport2 = L"COM5";
qDebug() << mccommport_string << mccommport << mccommport2;
它给出的qDebug输出是:
"COM5" 0x15cd542 0xe814a2
如果我尝试使用mccommport2与串口通信,它可以工作,如果我尝试使用mccommport它不会。我是c ++的新手所以我不确定这些是否应该相同......任何帮助都将不胜感激。
答案 0 :(得分:1)
将QString
数据转换为const wchar_t*
的更简单方法是使用toStdWString()
方法:
QString mccommport_string = "COM5";
std::wstring com5_str(mccommport_string.toStdWString());
const wchar_t* mccommport = com5_str.c_str();
L在&#34; COM5&#34;?之前做了什么?
这意味着wide string literal。