在c中将结构转换为char数组

时间:2016-10-06 12:56:05

标签: c arrays struct

我在下面定义了一个结构,用于通过uart发送的帧的内容。

我使用build_uart_frame()填充框架。

我有一个函数write_device()来通过uart传输帧。

我的问题是,如何将结构传递给write_device(),因为它期望指向char数组的指针。

我应该尝试将stuct变量rdata转换为char array还是我接近这个错误?

这个问题与我的另一篇文章有​​关(我不确定你是否允许这样做)。我知道这不是代码编写服务,我尽量避免提问,但我有点超出我的深度。

这个问题发布在这里:related question

非常感谢

typedef struct uart_frame {
  uint8_t sof;                    /* 1 byte  */
  uint8_t len;                    /* 1 bytes */
  uint8_t cmd0;                   /* 1 byte  */
  uint8_t cmd1;
  char data[11];                 
  unsigned char fcs;              /* 1 byte  */                      
} uart_frame_t;

//------------------------------------------------------------------------------
// Global uart frame
uart_frame_t rdata;
//------------------------------------------------------------------------------

// Populate the frame

int build_uart_frame() {

uart_frame_t *rd = &rdata; //pointer variable 'rd' of type uart_frame    

// common header codes
rd->sof = 0xFE;
rd->len = 11;
rd->cmd0 = 0x22;
rd->cmd0 = 0x05;
snprintf(rd->data, sizeof(rd->data), "%s", "Hello World");
rd->fcs = calcFCS((unsigned char *)rd, sizeof(uart_frame_t) - 1);
return 0;
}

//--------------------------------------------------------------------------
int write_device(char *txbuf, int size) {
DWORD BytesWritten;

  isolator_status = FT_Write(isolator_handle, txbuf, size, &BytesWritten); 
  if (isolator_status == FT_OK) {
    return 0;
  }
  return -1;

}
//--------------------------------------------------------------------------
int main() {

  build_uart_frame();
  write_device(??);

  return 0;
}

1 个答案:

答案 0 :(得分:0)

    int main() {


      char* tempBuf = (char*) &rdata;
      /* Clear the buffer*/
      memset( (char*)rdata, 0x00, sizeof(rdata));
      build_uart_frame();
      write_device(tempBuf, sizeof(uart_frame_t));
      /* You can have problem with BYTE alignement so you can check the result of sizeof(uart_frame_t) if it is really equal to declaration */


      return 0;

}
相关问题