Correct, portable way to interpret buffer as a struct

前端 未结 2 732
一向
一向 2020-12-13 02:28

The context of my problem is in network programming. Say I want to send messages over the network between two programs. For simplicity, let\'s say messages look like this, a

2条回答
  •  渐次进展
    2020-12-13 02:50

    The only correct way is, as you surmised, to copy the data from the char buffer into your structure. Your other alternatives violate the strict alias rules, or the one-member-of-union-active rule.

    I do want to take one more moment to remind you that even if you do this on a single host and byte order doesn't matter you still have to make sure that both ends of the connection arae built with the same options and that the struct is padded in the same way, the types are the same size, etc. I suggest taking at least a small amount of time considering a real serialization implementation so that if you ever need to support a wider array of conditions you don't have a big update in front of you then.

提交回复
热议问题