2016-12-21 4 views
0

私は__attribute__((packed))というタグが付けられた多数の構造体を定義する第三者のライブラリ(mavlink)を使用していますので、シリアル接続を介して効率的に送信できます。 C++アプリケーションで使用しています)。私がそれらを受け取って再構築するとき、私はそれらにタイムスタンプフィールドを追加したいと思います。私は最も簡単な方法は、既存の構造体を継承する新しい構造体を作成することだと思います。即ちmavlinkライブラリでこの構造体が定義されている:パックされたCの構造体を継承する

MAVPACKED__attribute__((packed))を適用するマクロある
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; 

sizeof(mavlink_heartbeat_t)戻っ9.私は、

struct new_heartbeat_t : mavlink_heartbeat_t 
    { 
     uint64_t timestamp; 
    }; 

sizeof(new_heartbeat_t)リターン24を定義する7つのパディングバイトが追加されているように、それは(バイト16のタイムスタンプ開始するように、私はmavlink_heartbeat_tの最後まで引き受ける)に見えるよう

がある場合これをやっているときに気が付かなければならないことや良い方法があるでしょうか?

+0

カプセル化は長期的にはより保守かもしれません。 –

+0

構造体に属性__((__ packed))属性を適用してサイズを確認できます。 – manu

+0

@RichardHodgesどういう意味ですか? 'mavlink_heartbeat_t'を継承する代わりに、それを新しい構造体のプライベートメンバにして、' mavlink_heartbeat_t'の各メンバにアクセサを提供することを意味しますか? –

答えて

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); 

} 
関連する問題