Casting one C structure into another

前端 未结 8 677
再見小時候
再見小時候 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.

提交回复
热议问题