Go Down

Topic: Passing a function to a constructor (Read 715 times) previous topic - next topic

edringel

Hi All,
I am writing a library to support the 74C923, a chip that manages a 4X5 keypad. (I will post the library on the playground once completed) It's working well in its present form, but what I would like to do is to be able to pass a function to the class constructor and have the class remember the function throughout the program's running.  This would be similar to the attachInterrupt() routine.  The user would write the function that would handle key presses; the rest of the housekeeping would be handled by the chip and the class.

I've researched this a bunch and am having difficulty with the code. I think I understand how to pass a function as a parameter to another function, but I don't know how to store the address in a variable in the class. Or can't I do that at all?

Appreciate any help offered.

Thanks.
Ed Ringel

montecito

#1
Jun 30, 2011, 04:16 am Last Edit: Jun 30, 2011, 04:19 am by montecito Reason: 1
You can pass a function pointer to a constructor, store it, and call it like this:

Code: [Select]

class foo {
public:
 foo(int (*p)(int)) : _p(p) { }

 int doit(val) {
   return _p(val);
 }

private:
 int (*_p)(int);
};

int doubleit(int val) {
 return val*2;
}

int main() {
 foo f(doubleit);
 int result = f.doit(2);

...
}




You will need to adapt to the particular signature of the function you wish to store.  But this gives the basic syntax and paradigm.


marklar

#2
Jun 30, 2011, 04:37 am Last Edit: Jun 30, 2011, 04:40 am by marklar Reason: 1
Someone beat me to the post but since I created a working example, here it is.

Code: [Select]


class HasCallback {

public:

  void (*cmdCallback)(int action);

  HasCallback(void (*cmd)(int cmd)) {
    this->cmdCallback = cmd;
  };

  ~HasCallback() {
  };

  void testCallack(int testAction){
    cmdCallback(testAction);
  }


};


void demoCallback(int action){
   Serial.println(action, DEC);
}
HasCallback hc = HasCallback(&demoCallback);


void setup(){
  Serial.begin(9600);
}

int currentAction = 0;

void loop(){
  currentAction++;
  if (currentAction > 10000){
     currentAction = 1;
  }
 
  hc.testCallack(currentAction);
  delay(100);
 
}


edringel

Thank you both. The information has been most helpful.

Ed

Go Up