开发者

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 typedefs in your code. Try this:

http://codepad.org/frysgQte


The problem is your typedef statements. RF12Message::data is not a union of 40 uint8_ts and a MessageNodeFound; it is a datatype consisting of those things.

A similar problem will affect your declaration of MessageNodeFound. Remove both typedefs, 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜