How to use structure with dynamically changing size of data?

后端 未结 3 1891
青春惊慌失措
青春惊慌失措 2021-01-27 06:38

Question for C only, C++ and vectors do not solve problem.

I have such structure:

typedef __packed struct Packet_s
{
  U8  head;
  U16 len;
  U32 id;
  U         


        
3条回答
  •  余生分开走
    2021-01-27 07:13

    Is it possible to use my structure if field "DATA" is longer than 1 byte?

    No, since it has only room for 1 data byte. But you can use a slightly modified version of your structure.

    typedef __packed struct Packet_s
    {
      U8  head;
      U16 len;
      U32 id;
      U8  data[DATALENMAX]; // define appropriately
      U8  end;
      U16 crc;
    } Packet_t, *Packet_p;
    

    Of course, you'd have to adapt the copying accordingly:

    memcpy(&Packet, &Buffer, buffer_len), memmove(&Packet.end, &Packet.data[buffer_len-7-3], 3);
    

    Regarding the added problems, it's necessary to pass the data length to SendResponce():

    SendResponce(rspData, sizeof rspData);
    
    void SendResponce(uint8_t* data_rsp, int datalen)
    {
      Packet_t ResponceData;
      uint16_t crc;
      uint8_t *data;
    
      ResponceData.head  = 0x24;
      ResponceData.len   = 7+datalen+3; // HERE WAS PROBLEM ONE
      ResponceData.id   = SPECIAL_ID_X;
      memcpy(ResponceData.data, data_rsp, datalen); // HERE WAS PROBLEM TWO
      ResponceData.data[datalen] = 0x0D; // symbol '\r'
      data = (uint8_t*)&ResponceData;
      crc = GetCrc(data, 7+datalen+1); // last 2 bytes with crc
      ResponceData.crc = crc;//(ack_crc >> 8 | ack_crc);
      memmove(ResponceData.data+datalen+1, &ResponceData.crc, 2);
      SendData((U8*)&ResponceData, ResponceData.len);  // Send rsp packet
    }
    

提交回复
热议问题