简体   繁体   English

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

[英]Converting a struct to a char array in c

I have a struct defined below for the contents of a frame to be sent over uart. 我下面定义了一个结构,用于通过uart发送的框架的内容。

I populate the frame using build_uart_frame() . 我使用build_uart_frame()填充框架。

I have a function write_device() to transmit the frame over uart. 我有一个函数write_device()通过uart传输帧。

My question is, how do I pass the struct to write_device() as it is expecting a pointer to a char array. 我的问题是,如何将结构传递给write_device()因为它期望指向char数组的指针。

Should I try convert the stuct variable rdata to a char array or am I approaching this wrong? 我应该尝试将stuct变量rdata转换为char array还是遇到这种错误?

This question is related to another post that I have (I'm not sure if I your allowed do this). 这个问题与我的另一篇帖子有关(我不确定您是否允许这样做)。 I understand that this is not a code writing service, I do try avoid asking questions but I'm a bit out of my depth. 我知道这不是代码编写服务,但我会尽量避免提出问题,但我有点不了解。

That question is posted here: related question 该问题在此处发布: 相关问题

Many thanks 非常感谢

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;
}
    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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM