Cast array of bytes to POD

前端 未结 2 1804
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 05:13

Let\'s say, I have an array of unsigned chars that represents a bunch of POD objects (e.g. either read from a socket or via mmap). Which types they represent and at what positi

2条回答
  •  时光取名叫无心
    2021-02-04 05:50

    Using a union allows to escape anti-aliasing rule. In fact that is what unions are for. So casting pointers to a union type from a type that is part of the union is explicitly allowed in C++ standard (Clause 3.10.10.6). Same thing is allowed in C standard (6.5.7).

    Therefore depending on the other properties a conforming equivalent of your sample can be as follows.

    union to_pod {
        uint8_t buffer[100];
        Pod1 pod1;
        Pod1 pod2;
        //...
    };
    
    uint8_t buffer[100]; //filled e.g. from network
    
    switch(buffer[0]) {
        case 0: process(reinterpret_cast(buffer + 4)->pod1); break;
        case 1: process(reinterpret_cast(buffer + 8 + buffer[1]*4)->pod2); break;
        //...
    }
    

提交回复
热议问题