How to cast C struct just another struct type if their memory size are equal?

后端 未结 2 1658
有刺的猬
有刺的猬 2021-01-02 05:33

I have 2 matrix structs means equal data but have different form like these:

// Matrix type 1.
typedef float Scalar;
typedef struct { Scalar e[4]; } Vector;
         


        
2条回答
  •  不知归路
    2021-01-02 06:00

    Probably the best solution would be to combine your two structs into a union. If you want to interpret the same data in two different ways then it's the obvious choice. The alternative is to use pointer casts, but that's ugly, breaks aliasing rules, and can hide errors that might otherwise be reported by the compiler.

    typedef float Scalar;
    typedef struct { Scalar e[4]; } Vector;
    typedef struct { Vector e[4]; } Matrix;
    
    struct CATransform3D
    {
       CGFloat m11, m12, m13, m14;
       CGFloat m21, m22, m23, m24;
       CGFloat m31, m32, m33, m34;
       CGFloat m41, m42, m43, m44;
    };
    typedef struct CATransform3D CATransform3D;
    
    typedef union
    {
        CATransform3D t;
        Matrix m;
    } UMatrix;
    
    CATransform3D CATransform3DMakeScale (CGFloat sx, CGFloat sy, CGFloat sz);
    UMatrix um;
    um.t = CATransform3DMakeScale ( 1, 2, 3 );
    //
    // now you can just use um.m when you need to refer to the Matrix type...
    //
    

提交回复
热议问题