【问题标题】:QByteArray get the address of nth elementQByteArray 获取第 n 个元素的地址
【发布时间】:2016-02-26 19:06:17
【问题描述】:

我有以下代码需要从纯 c++ 转换为 qt:

// txMessage and UserData are char arrays
memcpy(&txMessage[18], UserData, 8);

所以我的转换是这样的:

QByteArray txMessage;
txMessage.resize(26);
    :
    :
memcpy(&(txMessage.data()[18]), UserData, 8);

所以这应该可以,但看起来很乱。我必须使用 data() 函数获取数据指针,然后使用 [18] 引用元素 18,然后使用 & 获取该元素的地址。

我在网上浏览了整个 QByteArray 文档,看不到另一个返回 char* 和 operator [] 的函数只返回一个临时变量,所以无法解决这个问题。但是 QByteArray 有很多选项/功能,也许我错过了什么?有人找到/得到了更好的方法来获取 QByteArray 中第 n 个元素的地址吗?

编辑 QByteArray 中似乎没有记录一些内容:

  • char* data_ptr() - 同样的问题
  • char* 指针 - 表示它具有 stl 可比性,但我可以使用它/信任它吗?

【问题讨论】:

  • txMessage.data() + 18,好一点。
  • @Holt 哦,是的.... 好一点 :) +1
  • 您尝试过replace 方法吗? txMessage.replace(18, 8, UserData);
  • @Holt marvelous!,我认为我的方向是错误的:)...坚持作为答案,如果你愿意,我会标记它:)

标签: c++ qt qbytearray


【解决方案1】:

您应该改用replace 方法:

txMessage.replace(18, 8, UserData, 8) ;

如果您使用的 Qt 版本低于 4.7,但您的 UserData 变量以空值结尾,那么只需:

txMessage.replace(18, 8, UserData) ;

除此之外:

memcpy(txMessage.data() + 18, UserData, 8);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2012-02-02
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2018-08-07
    相关资源
    最近更新 更多