Casting one C structure into another

前端 未结 8 675
再見小時候
再見小時候 2020-11-27 03:30

I have two identical (but differently named) C structures:

typedef struct {
      double x;
      double y;
      double z;
} CMAcceleration;


typedef struc         


        
相关标签:
8条回答
  • 2020-11-27 04:08

    A safe (albeit somewhat convoluted) way to do it would be to use a union:

    union { CMAcceleration a, Vector3d v } tmp = { .a = acceleration };
    vector = tmp.v;
    

    Values are reinterpreted (since C99) when the accessed member is not the last set one. In this case, we set the acceleration and then we access the vector, so the acceleration is reinterpreted.

    This is the way the NSRectToCGRect function is implemented, for example.

    0 讨论(0)
  • 2020-11-27 04:13

    memcpy(&vector, &acceleration, sizeof(Vector3d));

    Please note that this works only, if the physical layout of the structs in memory are identical. However, as @Oli pointed out, the compiler is not obliged to ensure this!

    0 讨论(0)
提交回复
热议问题