c++我如何修改代码发送字节从一个串行端口在范围0x00到0xFF的代码,只编译范围0x00到0x7F



我继承了一些在Windows中设置串口的c++代码。该代码包含以下声明和方法,为了解决这个问题,我对其进行了简化。

std::queue<std::string> m_queue;
SendMsg( const char* dataBuff, unsigned int dataBuffSz )
{
// Insert into the end of the queue to send
m_queue.emplace( dataBuff, dataBuffSz );

}

如果我创建一个合适的对象来调用SendMsg,那么以下内容是有效的,并成功地通过串行链接传输

mySerialLinkObject->SendMsg( "Hello", 5 );
// or alternatively
char hexBytes[4] = { 0x01, 0x02, 0x0F, 0x7F };
mySerialLinkObject->SendMsg( hexBytes, 4 );

我对这个链接的具体要求是它能够在0x00到0xFF的范围内发送十六进制字节,但是如果我声明

char hexBytes[2] = { 0x80, 0xFF };

在Visual Studio 2015中,我从上面的hexBytes行声明中得到以下构建输出

错误C2220:警告被视为错误-没有生成'object'文件从'int'到'char'的转换需要一个窄化转换注意:为了简化迁移,请考虑在编译器的版本中临时使用/Wv:18标志,您可以使用该版本进行无警告编译' initialization ':截断常量

如果我改变我的hexBytes定义如下

uint8_t hexBytes[2] = { 0x80, 0xFF }; //unsigned char fixed width
这修复了初始编译器错误,如果我重载SendMsg方法到
SendMsg( const uint8_t* dataBuff, unsigned int dataBuffSz )
{
// Insert into the end of the queue to send
m_queue.emplace( dataBuff, dataBuffSz );

}

然后我得到一大堆std::queue相关的编译错误

xmemory0(737):错误C2664: 'std::basic_string<char,std::char_traits,std::allocator>::basic_string(std::initializer_list<_Elem>,const std::allocator &)':无法将参数1从'const uint8_t *'转换为'const std::basic_string<char,std::char_traits,std::allocator>;,"1比;与1比;(

这不是我的代码,所以我真的不明白它最初是怎么做的,当它把char*参数放入std::string队列,为什么我不允许编译器放置&;unsigned char*&;;进入std::string队列

我不知道解决这个问题的最好方法是什么。

我修复初始的C4838错误时,通过做某种形式的转换声明hexBytes,在这种情况下,我不知道如何?

或者我是否尝试修复我得到的std::queue错误。我也不确定最好的方法是什么

根据ISO c++标准,char是否与signed charunsigned char具有相同的表示是由实现定义的。

在Microsoft Visual Studio上,在默认设置下,char具有与signed char相同的表示,它能够表示-128127范围内的数字。

因此,不可能将0x80(十进制128)到0xFF(十进制255)范围内的数字放入char数组。但是,您可以将其放入char数组中,通过写入

,使其具有与uint8_t

类型数组相同的内存表示。char hexBytes[2] = { (char)0x80, (char)0xFF };

代替:

char hexBytes[2] = { 0x80, 0xFF };

另一方面,对每个值执行强制转换将非常麻烦。因此,将数组定义为字符串字面值 可能会更容易一些。char hexBytes[] = "x80xFF";

将浪费一个字节作为结束null字符。

或者您可以将数组定义为类型uint8_t,并将衰变指针强制转换为char*,如下所示:

uint8_t hexBytes[2] = { 0x80, 0xFF };
mySerialLinkObject->SendMsg( reinterpret_cast<char*>(hexBytes), 2 );

这样,就不需要重载SendMsg函数,也不会出现任何与std::queuestd::basic_string相关的编译错误。

最新更新