Cast array of bytes to POD

前端 未结 2 1782
被撕碎了的回忆
被撕碎了的回忆 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:52

    The most correct way is to create a (temporary) variable of the desired POD class, and to use memcpy() to copy data from the buffer into that variable:

    switch(buffer[0]) {
        case 0: {
            Pod1 var;
            std::memcpy(&var, &buffer[4], sizeof var);
            process(var);
            break;
        }
        case 1: {
            Pod2 var;
            std::memcpy(&var, &buffer[8 + buffer[1] * 4], sizeof var);
            process(var);
            break;
        }
        //...
    }
    

    There main reason for doing this is because of alignment issues: the data in the buffer may not be aligned correctly for the POD type you are using. Making a copy eliminates this problem. It also allows you to keep using the variable even if the network buffer is no longer available.

    Only if you are absolutely sure that the data is properly aligned can you use the first solution you gave.

    (If you are reading in data from the network, you should always check that the data is valid first, and that you won't read outside of your buffer. For example with &buffer[8 + buffer[1] * 4], you should check that the start of that address plus the size of Pod2 does not exceed the buffer length. Luckily you are using uint8_t, otherwise you'd also have to check that buffer[1] is not negative.)

提交回复
热议问题