I have a lot of legacy code that uses a function pointer as an argument of the form double (*f)(double). Now I have a requirement where I need to call this function from a class but function definition uses member variables. What do I do to solve this issue? For example,
void legacy_function(double (*f)(double)) { .... }
class myclass {
double a;
double b;
double c;
void mymethod(...) {
// need to call legacy_function() such that it uses a and b with one unknown
// a+b*x
}
Note that I cannot change definitions or declarations in legacy code.
I hope this is making sense. thanks for suggestions..
There’s no clean way to solve this problem. It has no elegant solution within the bounds of the standard language.
One thing you can do is to provide a global or static variable that will serve as
thispointer for the intermediate callback wrapper function (see below), and write a static intermediate callback wrapper function which will delecate the call to a non-static class methodAlso write the actual callback implementation in
myclassNow you can initialize
myclass_thisand use the intermediate callback wrapper from insidemymethodAll this, of course, is terribly inelegant since it relies on global or static variables and therefore is non-reentrant.
There are alternative methods, which all happen to be non-portable and non-standard. (Read about closures and delegates).