0 votes
29 views

I need to pass a pointer to a special type of structure as event_data parameter in ESP-IDF. However, as per the `event_loop documentation:

Posts an event to the specified event loop. The event loop library
keeps a copy of event_data and manages the copy’s lifetime
automatically (allocation + deletion); this ensures that the data the
handler recieves is always valid.

Currently I pass the pointer as usual like following:

esp_event_post_to(relay_chn_event_loop,
                      RELAY_CHN_CMD_EVENT,
                      cmd,
                      chn_ctl,
                      sizeof(relay_chn_ctl_t*),
                      portMAX_DELAY); 

Then I receive it in the handler like following:

static void relay_chn_event_handler(void* handler_arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    relay_chn_ctl_t* chn_ctl = (relay_chn_ctl_t*) event_data;
    ...
}

But this way, the memory addres isn't passed as expected and the chn_ctl in the handler has a different memory address. Eventually I get the following error that indicates a system crash for a NULL pointer right after the esp_event_post_to is executed:

Guru Meditation Error: Core 0 panic'ed (LoadProhibited). Exception
was unhandled.

What is the proper way to pass a pointer through the event_data parameter?

by (1.4k points) | 29 views

1 Answer

0 votes
Best answer

Since the event_loop library makes a copy of the event_data parameter, the original pointer value should be passed by wrapping it by another pointer, instead of passing the original pointer directly.

Here is the fixed version of the code:

esp_event_post_to(relay_chn_event_loop,
                      RELAY_CHN_CMD_EVENT,
                      cmd,
                      &chn_ctl,
                      sizeof(chn_ctl),
                      portMAX_DELAY);

And the handler:

static void relay_chn_event_handler(void* handler_arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    relay_chn_ctl_t* chn_ctl = *(relay_chn_ctl_t**) event_data;
    ...
}

This way, the original pointer value will be preserved by pointing it by another pointer:

wrapper_pointer->original_pointer
by (1.4k points)
selected by
Welcome to Kozmotronik Q&A, where you can ask questions and receive answers from other members of the community.