Pass extra parameter into callback function

Hi everyone, I need help with feature that pass additional parameter into callback function


/* Library code */
typedef void (*cb)(int x);

bool libraryFunc(int param, cb cbFunc) {
 // doing something and then call cb
}
/* end Library code */

void callback(int x, int extraData) {

}

// Here I need wrap callback function to add extraData value
 libraryFunc(3, callback)

What I was trying to do:

  1. using std::bind (it looks like not available for arduino (()
  2. Using lambda function, it was hard to cast lamda to function pointer type especially if these is captured variables

Might be somebody has a other idea how to do it.
The library code can not be changed

Which Arduino board? You're correct that std::bind and std::function are not available for AVR-based boards (Uno, Mega, etc). However, they are available for ARM and ESP32/8266 - based boards.

If extraData is known at compile time, you could use a template. E.g.,

bool libraryFunc(int param, cb cbFunc) {
  cbFunc(param);
  return false;
}

template <int extraData> void callback(int x) {
  Serial.println(x * extraData);
}

void setup() {
  Serial.begin(9600);
  libraryFunc(3, callback<10>);  // Prints "30";
}
1 Like

Arduino Nano currently, got it, thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.