0

POD構造体がAと言う場合、私はこれを行います:

char* ptr = reinterpret_cast<char*>(A);
char buf[20];
for (int i =0;i<20; ++i)
   buf[i] = ptr[i];
network_send(buf,..);

受信側のリモートボックスが必ずしも同じハードウェアまたはOSであるとは限らない場合、これを安全に実行して「シリアル化を解除」できますか?

void onRecieve(..char* buf,..) {
  A* result = reinterpret_cast<A*>(buf); // given same bytes in same order from the sending end

「結果」は常に有効ですか?C ++標準はPOD構造で述べており、reinterpret_castの結果は最初のメンバーを指す必要がありますが、受信側が別のプラットフォームであっても、実際のバイト順序も正しいことを意味しますか?

4

2 に答える 2

1

いいえ、あなたがすることはできません。"down" をchar*にのみキャストでき、オブジェクト ポインタに戻すことはできません。

  Source                  Destination
     \                         /
      \                       /
       V                     V
 read as char* ---> write as if to char*

コード内:

Foo Source;
Foo Destination;

char buf[sizeof(Foo)];

// Serialize:
char const * ps = reinterpret_cast<char const *>(&Source);
std::copy(ps, ps + sizeof(Foo), buf);

// Deserialize:
char * pd = reinterpret_cast<char *>(&Destination);
std::copy(buf, buf + sizeof(Foo), pd);

一言で言えば、オブジェクトが必要な場合、オブジェクトが必要です。ランダムなメモリ位置実際にオブジェクトではない場合 (つまり、目的の型の実際のオブジェクトのアドレスでない場合) にオブジェクトであると偽ることはできません。

于 2012-01-30T05:02:01.537 に答える
0

これにはテンプレートを使用し、コンパイラに処理させることを検討してください。

template<typename T>
struct base_type {
    union {
        T    scalar;
        char bytes[sizeof(T)];
    };
    void serialize(T val, byte* dest) {
        scalar = val;
        if is_big_endian { /* swap bytes and write */ }
        else { /* just write */ }
    }
};
于 2013-06-30T15:56:53.107 に答える