如何解决C 缓冲区指针 问题到目前为止我尝试了什么示例代码
问题
我目前正在使用带有 esp-idf 的 ESP-NOW。以下是他们 espnow 示例的片段。我需要一些帮助来确定这条线的含义,但我不太确定要谷歌搜索什么。有人能指出我正确的方向吗?
example_espnow_data_t *buf = (example_espnow_data_t *)send_param->buffer;
到目前为止我尝试了什么
我似乎无法在网上找到任何指南,因为我不知道该用什么 google。根据我所能找到的,我的猜测是 send_param
缓冲区参数被解析为 buf
的 example_espnow_data_t
指针。我的理解正确吗?
示例代码
example_espnow_send_param_t
是一个 typdef struct
,其中 buffer
作为参数之一。然后将发送参数分配并填充到 send_param
内存块。然后将其传递给数据准备函数。
// code is truncated
typedef struct { // from header files
bool unicast; //Send unicast ESPNOW data.
bool broadcast; //Send broadcast ESPNOW data.
.
.
} example_espnow_send_param_t;
typedef struct { // from header files
uint8_t type; //Broadcast or unicast ESPNOW data.
.
.
} __attribute__((packed)) example_espnow_data_t;
send_param = malloc(sizeof(example_espnow_send_param_t));
memset(send_param,sizeof(example_espnow_send_param_t));
send_param->unicast = false;
send_param->broadcast = false;
.
.
example_espnow_data_prepare(send_param);
void example_espnow_data_prepare(example_espnow_send_param_t *send_param)
{
example_espnow_data_t *buf = (example_espnow_data_t *)send_param->buffer;
assert(send_param->len >= sizeof(example_espnow_data_t));
.
.
}
解决方法
您已经从 struct example_espnow_send_param_t
的定义中截断了相关部分 - 字段 buffer
:)
/* Parameters of sending ESPNOW data. */
typedef struct {
...
uint8_t *buffer; //Buffer pointing to ESPNOW data.
...
} example_espnow_send_param_t;
无论如何,该函数接收一个指向 struct example_espnow_send_param_t
的指针作为输入变量 send_param
。有问题的行从该结构中选择字段 buffer
。 buffer
只是持有一个指向 example_espnow_send_param_t
所知的原始数据的指针。
然后将这个指向原始数据的指针转换为指向 struct example_espnow_data_t
的指针 - 从而假设这是原始数据实际保存的内容。最后,它分配一个正确指针类型的新变量并将转换结果赋给它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。