6 years, 1 month ago.

Mailbox and different message types

What would be the suggested way to solve this:

I would like to use the mailbox to send different message type one of which would contain a pointer to a char array:

Here are the message types:

mail box definition

Mail<mail_t, 32> mail_box;

the message types

struct mail_t
{
    ID msgID;
};

struct msg1 : mail_t 
{ 
    uint16_t length;
    char * msg;
};

struct msg2: mail_t 
{ 
    uint16_t length;
    uint16_t length;
    uint16_t length;
};

How should I handle this when placing different message types onto the mailbox....

I did see the suggestion of using a union instead but can a pointer be placed in a union? The char * msg could be quite big...

1 Answer

6 years, 1 month ago.

The normal method to do this would be as you say to have a union of the different message types. I'm not sure why you care concerned about lengths, both of your message types are 6 bytes of data. The char *msg is only a pointer and so will be 4 bytes. Remember it is only a pointer to where the text message is, it's not the actual message. The memory containing the message needs to be handled somewhere else in your code. If you're going to queue up multiple messages then you may have to allocate the memory for the messages dynamically in which case don't forget to free it before discarding the message structure.

Accepted Answer