[英]How to cast from const char* to a struct?
During the development of a Qt application for Embedded Linux (where improvements in performance are really welcomed), I came across the necessity to cast from a array of chars to a given struct. 在针对嵌入式Linux的Qt应用程序的开发过程中(在性能上确实受到了欢迎),我遇到了将一系列字符转换为给定结构的必要性。 Till now, that was being done with the code: 到现在为止,这是通过代码完成的:
MyStruct* const my_struct = reinterpret_cast< MyStruct* >(qbytearray.data());
while data()
being a member of the Qt class QByteArray
that transforms the byte array to a char*
. 而data()
是Qt类QByteArray
的成员,该类将字节数组转换为char*
。 In doing this, tough, it makes a deep copy of the data, which is not good given the extra processing. 这样做很困难,它会复制数据的深层副本,考虑到额外的处理,这是不好的。 Since I want to only read the data (the struct casted will never be used to edit), the alternative method QByteArray::constData()
is preferable, since it doesn't make a deep copy, but in contrast returns a const char*
instead of char*
. 由于我只想读取数据( QByteArray::constData()
的结构永远不会用于编辑),因此QByteArray::constData()
替代方法QByteArray::constData()
,因为它不会进行深层复制,但相反会返回const char*
代替char*
。
The question is: how I should do the casting now? 问题是:我现在应该如何铸造? I tried to use const_cast without success. 我尝试使用const_cast失败。
MyStruct* const my_struct = const_cast< MyStruct* >(qbytearray.constData()); // compile error
const MyStruct* const my_struct = const_cast< MyStruct* >(qbytearray.constData()); // compile error
and reinterpret_cast
also didn't work because "it casts away the qualifiers", which is expected. 和reinterpret_cast
也不起作用,因为“它抛弃了限定符”,这是预料之中的。 The closest way I was capable of doing this was by first casting to char*
and later to the struct: 我能够执行此操作的最接近方法是先转换为char*
,然后转换为struct:
MyStruct* const my_struct = (MyStruct*)const_cast< char* >(qbytearray.constData());
but I get the feeling that not only this is "circle around" the problem, but also that the casting from char*
to MyStruct*
will ultimately sacrifice the processing improvement I was desiring. 但是我感觉不仅这是问题的解决,而且从char*
到MyStruct*
最终将牺牲我想要的处理改进。
So how do this casting correctly? 那么如何正确铸造呢?
This has nothing to do with const_cast
. 这与const_cast
无关。 You are not trying to cast away const
-ness. 您不是要放弃const
-ness。
const MyStruct* my_struct = reinterpret_cast<const MyStruct* >(qbytearray.constData());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.