Casting one C structure into another

前端 未结 8 673
再見小時候
再見小時候 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 03:46

    That's your only solution (apart from wrapping it into a function):

    vector.x = acceleration.x;
    vector.y = acceleration.y;
    vector.z = acceleration.z;
    

    You could actually cast it, like this (using pointers)

    Vector3d *vector = (Vector3d*) &acceleration;
    

    but this is not in the specs and therefore the behaviour depends on the compiler, runtime and the big green space monster.

    0 讨论(0)
  • 2020-11-27 03:50

    Another version of the utility function making use of C99:

    static inline struct Vector3d AccelerationToVector(struct CMAcceleration In)
    {
        return (struct Vector3d){In.x, In.y, In.z};
    }
    

    With the compiler optimization turned up (e.g., -Os), this should turn into absolutely no object code when invoked.

    0 讨论(0)
  • 2020-11-27 03:56

    You could use a pointer to do the typecast;

    vector = *((Vector3d *) &acceleration);
    
    0 讨论(0)
  • 2020-11-27 03:58

    This is achieved easily through a union:

    typedef struct {
          double x;
          double y;
          double z;
    } CMAcceleration;
    
    typedef struct {
        double x;
        double y;
        double z;
    } Vector3d;
    
    typedef union {
        CMAcceleration acceleration;
        Vector3d vector;
    } view;
    
    int main() {
        view v = (view) (Vector3d) {1.0, 2.0, 3.0};
        CMAcceleration accel = v.acceleration;
        printf("proof: %g %g %g\n", accel.x, accel.y, accel.z);
    }
    
    0 讨论(0)
  • 2020-11-27 04:02

    You use an utility function for that:

    void AccelerationToVector( struct CMAcceleration* from, struct Vector3d* to )
    {
         to->x = from->x;
         to->y = from->y;
         to->z = from->z;
    }
    
    0 讨论(0)
  • 2020-11-27 04:08

    Why dont you use.

    typedef CMAcceleration Vector3d;
    

    (instead of creating a whole new structure)

    in that case vector = acceleration; compiles just fine.

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