I\'m writing a C program that would, if had been a part of the language, benefit from, partial function application. I need to supply a function pointer with a fixed signatu
I don't know of any straight foward way do do what you want, since C doesn't support closures or any other way to pass "hidden parameters" to your functions (without using globals or static variables, strtok style)
You seem to come from a FP background. In C everything has to be done by hand and I'd risk saying that in this case it might be better to try to model things in OO style instead: turn your functions into "methods" by making them receive an extra argument, a pointer to a struct of "inner attributes", the this
or self
. (If you happen to know Python this should be very clear :) )
In this case, for example, func1
might turn into something like this:
typedef struct {
int code;
char * name;
} Joystick;
Joystick* makeJoystick(int code, char* name){
//The constructor
Joystick* j = malloc(sizeof Joystick);
j->code = code;
j->name = name;
return j;
}
void freeJoystick(Joystick* self){
//Ever noticed how most languages with closures/objects
// have garbage collection? :)
}
void func1(Joystick* self){
func2(self->code, self->name);
}
int main(){
Joystick* joyleft = make_Joystick(10, "a string");
Joystick* joyright = make_Joystick(17, "b string");
func1(joyleft);
func1(joyright);
freeJoystick(joyleft);
freeJoystick(joyright);
return 0;
}