Question

I got a codebase which used to transfer several kinds of message on socket to another process and used a union for that

#define maxlen 60
typedef struct
{
    TYRES t[MAXLEN];
} TYRE_T;

typdef struct
{
    TUBES t[MAXLEN];
}TUBES_T;

typedef struct
{
    TYPE t[MAXLEN];
} TYPE_T;

typedef union
{
    TYRE_T tyres;
    TUBES_T tubes;
    TYPE_T type;
} messageunion;

typedef struct
{
    int code;
    messageunion msg;
} socketmessage_t;

enum msgtype
{
   INVALID = -1;
   TYRES,
   TUBES,
   TYPES
};

//On clientside
processMessage(socketmessage_t* msg)
{
    switch(msg->code)
    {
        ....
    }
}

Now MAXLEN is not a macro but it will be run time variable evaluated by program. so I changed all array members to flexible array like this

typedef struct
{
int size;
TYRES t[];
}

My question is almost all socket functions needs size of buffer to receive message so how to calculate that size here? Thanks

Was it helpful?

Solution

First you should probably start using fixed-size integers, like uint32_t (from <cstdint>) for the sizes and message types.

Then the receiving application know how much to read to get the message type, and how much to read to get the size. Then simply read the specified number of bytes into the correct structure.

The important thing is that all structures in the union must start with a size member.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top