Search code examples
cnrf52

Trouble figuring out syntax for pointer casting


I was working today when I came across the following function:

void button_scheduler_event_handler(void *p_event_data, uint16_t event_size)
{
    button_handler(*((nrf_drv_gpiote_pin_t*)p_event_data));
}

with button handler defined as the following:

void button_handler(nrf_drv_gpiote_pin_t pin)

I'm not sure Í have encountered this syntax:

button_handler(*((nrf_drv_gpiote_pin_t*)p_event_data));

before and I am a bit bewildered. My first thought is that the syntax for calling button_handler should be:

button_handler(((*nrf_drv_gpiote_pin_t) *p_event_data));

I do however not have any good explanation for why.

Can anyone explain this?

Edit: after input from user UnholySheep


Solution

  • The p_event_data parameter is declared as a void *, meaning it could point to anything. However, based on the fact that it calls button_handler, it suggests that p_event_data is actually pointing to a nrf_drv_gpiote_pin_t.

    So first you need to cast the void * to a nrf_drv_gpiote_pin_t *:

    (nrf_drv_gpiote_pin_t  *)p_event_data
    

    Then you need to dereference that pointer:

    *((nrf_drv_gpiote_pin_t  *)p_event_data)
    

    And that's what gets passed to button_handler.