继承压缩的C结构

时间:2016-12-21 15:03:30

标签: c++ data-structures struct

我正在使用第三方库(mavlink)定义了许多都使用__attribute__((packed))标记的结构,因此可以通过串行连接有效地传输它们(它是用C编写的,我正在使用它在C ++应用程序中)。当我收到并重建它们时,我想给它们添加一个时间戳字段。我认为最简单的方法是创建一个继承现有结构的新结构。即在mavlink库中定义了这个结构:

MAVPACKED(
typedef struct __mavlink_heartbeat_t {
 uint32_t custom_mode; 
 uint8_t type; 
 uint8_t autopilot; 
 uint8_t base_mode; 
 uint8_t system_status;
 uint8_t mavlink_version; 
}) mavlink_heartbeat_t;

其中MAVPACKED是应用__attribute__((packed))的宏。 sizeof(mavlink_heartbeat_t)返回9.如果我定义

    struct new_heartbeat_t : mavlink_heartbeat_t
    {
        uint64_t timestamp;
    };

sizeof(new_heartbeat_t)返回24,所以看起来添加了7个填充字节(我假设结束了mavlink_heartbeat_t,以便时间戳从字节16开始。)

在做这个或者有更好的方法时,是否有任何问题或事情需要注意?

1 个答案:

答案 0 :(得分:0)

继承是是一种关系。

心跳的本地表示真的是一种有线消息吗?我对此表示怀疑。

但它可能合理包含一个。

我会把它封装成这样的东西:

#include <cstdint>
#include <cstddef>


typedef struct __attribute__((packed))  __mavlink_heartbeat_t {
 uint32_t custom_mode; 
 uint8_t type; 
 uint8_t autopilot; 
 uint8_t base_mode; 
 uint8_t system_status;
 uint8_t mavlink_version; 
} mavlink_heartbeat_t;


extern std::uint64_t now();
void sync_fetch_data(mavlink_heartbeat_t&);
void foo(uint8_t);

struct local_heartbeat
{

  mavlink_heartbeat_t const& get_io_buffer() const {
    return io_buffer_;
  }

  mavlink_heartbeat_t& prepare_receive() {
    request_timestamp_ = now();
    return io_buffer_;
  }

  void complete_receive() {
    response_timestamp_ = now();
  }


  std::uint64_t get_response_timestamp() const {
    return response_timestamp_;
  }

private:
  // stuff in here might have suspect alignment
  mavlink_heartbeat_t io_buffer_;

  // but these will be aligned for optimal performance
  std::uint64_t request_timestamp_;
  std::uint64_t response_timestamp_;
};



int main()
{

  // create my local representation
  local_heartbeat hb;

  // prepare it to receive data
  auto& buffer = hb.prepare_receive();

  // somehow populate the buffer
  sync_fetch_data(buffer);  // could be async, etc

  // notify the object that reception is complete
  hb.complete_receive();

  // now use the local representation
  foo(hb.get_io_buffer().system_status);

}
相关问题