Home > front end >  Passing a function pointer and a data pointer argument to a function that takes function pointer wit
Passing a function pointer and a data pointer argument to a function that takes function pointer wit

Time:02-26

from main I'm trying to pass a function with an address to a struct to another function I'm able to edit that takes a function pointer with a aoid pointer as an argument the function I'm trying to pass to attachReleased in main is tareFunc():

attachReleased(&Btn0Params,  tareFunc(&hx711));

and here's the code in another C file:

void attachReleased(btn_params_t *BtnParams, void (*BtnISR)(void *args)){
  // printf("Attached pin #%d\n ", BtnParams->BtnPin);
  BtnParams->ReleasedISR = BtnISR(&args);
  gpio_isr_handler_add(BtnParams->BtnPin, buttonISR, (btn_params_t *)BtnParams);
}

Is it possible to do what I'm trying to achieve with passing the function pointer and the argument pointer at the same time or do you have to separate them which is a little inconvenient?

CodePudding user response:

You're not actually passing a function pointer and its arguments here:

attachReleased(&Btn0Params,  tareFunc(&hx711));

What you're actually doing is calling tareFunc and passing its return value to attachReleased

You need to pass the parameter to tareFunc as a separate argument to attachReleased.

void attachReleased(btn_params_t *BtnParams, void (*BtnISR)(void *), void *args){
  // printf("Attached pin #%d\n ", BtnParams->BtnPin);
  //BtnParams->ReleasedISR = BtnISR(args);
  BtnISR(args);
  gpio_isr_handler_add(BtnParams->BtnPin, buttonISR, (btn_params_t *)BtnParams);
}

Which can then be called like this:

attachReleased(&Btn0Params,  tareFunc, &hx711);

Note also that since the function pointer BtnISR has a void return type, that there's no value to return and use.

CodePudding user response:

As coded you are passing the value returned by tareFunc to attachReleased so unless tareFunc returns void (*BtnISR)(void *args). It isn't possible to pass the value and the function ptr in this way. You could pass the arguments to the func ptr as an additional argument.

CodePudding user response:

If I understand your question correctly, what you want is something like this in your first file:

attachReleased(&Btn0Params, &tareFunc, &hx711);

and like this in your other C file:

void attachReleased(btn_params_t *BtnParams, void (*BtnISR)(void *), void *args)){
  // printf("Attached pin #%d\n ", BtnParams->BtnPin);
  BtnParams->ReleasedISR = (*BtnISR)(args);
  gpio_isr_handler_add(BtnParams->BtnPin, buttonISR, (btn_params_t *)BtnParams);
}
  • Related