c(++) union Data structure
I'm programming for a µC, i have following data Structure:
typedef struct
{
RF12Head head;
typedef union
{
uint8_t raw[40];
typedef struct
{
node_id nodeId;
uint8_t hierachyDepth;
} MessageNodeFound;
} d开发者_运维技巧ata;
} RF12Message;
A RF12Message contains a header an an data part. Now i want to have different message formats.
I want to be able to do something like this:
RF12Message msg;
memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly
//or indirectly:
msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;
but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?
thank you!
You have too many typedef
s in your code.
Try this:
http://codepad.org/frysgQte
The problem is your typedef
statements. RF12Message::data is not a union
of 40 uint8_t
s and a MessageNodeFound
; it is a datatype consisting of those things.
A similar problem will affect your declaration of MessageNodeFound
. Remove both typedef
s, and I think it should work.
For C++
The typedef declarations just declare a type. There is no data member called 'MessageNodeFound' or 'data' also for that matter.
This should give you an idea
typedef struct
{
typedef union
{
char raw[40];
typedef struct
{
int nodeId;
char hierachyDepth;
} MessageNodeFound;
MessageNodeFound m;
} Data;
Data d;
} RF12Message;
int main(){
RF12Message msg;
memset(&msg.d.raw, 0xEF, sizeof(msg.d.raw)); // fill in directly
//or indirectly:
msg.d.m.nodeId = 3;
msg.d.m.hierachyDepth = 2;
}
精彩评论