C 缓冲区指针

标签 c esp32 esp-idf

问题

我目前正在使用带有 esp-idf 的 ESP-NOW。以下是他们的 espnow 示例的片段。我需要一些帮助来确定此行的含义,但我不太确定要用谷歌搜索什么。有人能指出我正确的方向吗?

example_espnow_data_t *buf = (example_espnow_data_t *)send_param->buffer;

到目前为止我尝试了什么

我似乎无法在网上找到任何指南,因为我不确定要用谷歌搜索什么。根据我能找到的内容,我的猜测是 send_param 缓冲区参数被解析为 example_espnow_data_tbuf 指针。我的理解正确吗?

示例代码

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, 0, 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));
    .
    .
}

ESP32 repo

最佳答案

您已经从结构 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;

无论如何,该函数接收一个指向结构example_espnow_send_param_t 的指针作为输入变量send_param。有问题的行从该结构中选择字段 buffer。据 example_espnow_send_param_t 所知,buffer 只是指向一些原始数据的指针。

然后它将这个指向原始数据的指针转换为指向结构 example_espnow_data_t 的指针 - 从而假设这是原始数据实际保存的内容。最后,它分配一个正确指针类型的新变量并将转换结果赋值给它。

关于C 缓冲区指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66061238/

相关文章:

从包装宏内调用 Malloc

file - Micropython网络服务器: Serve large textfiles without memory allocation failure

java - 有没有办法在 ESP32 上使用 JMS(java 消息服务)?

python - 在 C 中创建 Python 扩展时出错

c - OpenCV中像素邻域差异的高效算法

cmake - 具有多个源文件的 ESP-IDF 项目

esp32 - 为什么我得到 Debug 异常原因 : Stack canary watchpoint triggered (main)?

esp32 - 为 ESP32 实现 Wi-Fi Direct

C/海湾合作委员会: dlopen() without needing dlsym()

build - PlatformIO 致命构建错误 : LiquidCrystal. h "No such file or directory"