Casting one C structure into another

Viewed 68060

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

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


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

Now I want to assign a CMAcceleration variable to a Vector3d variable (copying the whole struct). How can I do this?

I tried the following but get these compiler errors:

vector = acceleration;           // "incompatible type"
vector = (Vector3d)acceleration; // "conversion to non-scalar type requested"

Of course I can resort to set all members individually:

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

but that seems rather inconvenient.

What's the best solution?

9 Answers

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.

You could create a union with pointers that way you avoid copying data.

example :

struct Ocp1SyncHeader
{
    aes70::OCP1::OcaUint8 syncVal;          
    aes70::OCP1::Ocp1Header header;
};

struct convertToOcp1SyncHeader
{
    union
    {
        Ocp1SyncHeader* data;
        const uint8_t* src;
    };
    convertToOcp1SyncHeader& operator=(const uint8_t* rvalue) 
    { 
      src = (const uint8_t*)rvalue; 
      return *this; 
    }
};

** access like this:

convertToOcp1SyncHeader RecvData;
RecvData = src;  // src is your block of data that you want to access

** access members like this :

RecvData.data.header
Related