Why is there an endianness problem here?
I was reading up on this thread on pointer aliasing rules, and one answer gives the following example, which mentions a potential problem with endianness, I wanted to know if anyone could give me what the endianness problem is in the following code?
struct Msg
{
unsigned int a;
unsigned int b;
};
int main()
{
// Pass data to something; if the implementer of this API were
// strict-aliasing-aware, he would have taken a char*, not a unsigned int*
Msg* msg = new Msg();
msg->a = 1;
msg->b = 2;
// stupidBuffer is an alias for msg.
// yes I know there are endianess problems here (WHY??), but my API is stupid and
// only works for one platform
unsigned int* stupidBu开发者_如何学JAVAffer = reinterpret_cast<unsigned int*>(msg);
SendToStupidApi( stupidBuffer );
}
There isn't any endianness problem. As long as StupidApi doesn't involve sending it over a network or serialization between platforms, then there's no endianness issue at all.
Your messaging api should allow you to convert your local endianess to the network endianess (usually big endian) and back. By having a convention for the networking endianess, any machine can talk to any ohter machine on your network regardless of its own byte ordering.
Look in your api or examples for this. without knowing what you are using I am afraid we cannot help you much further than this.
精彩评论