'How to pass variable function pointer arguments to a function in C
I have a function that performs a search over elements of a mesh. I want that function to be able to call a variety of other functions to have them perform different actions over the mesh. For that purpose, is it possible to define a variable argument list where the variable arguments are all function pointers (all of the same "signature")? The variable function arguments are of the form:
int(*function)(struct mesh*, void*,int)
Here's a draft of what I thought could work (NOTE AppCtx is a struct, and num is the number of function arguments). My idea is to declare a function pointer of the above "signature" and then loop through the va_list's arguments. As I loop through these arguments I want the pointer thing to point to the different functions given to SearchFunction by means of the ....
#include <stdarg.h>
int SearchFunction(struct mesh,int depth,void* AppCtx,int num,...){
va_list valist;
int ii,jj, *Start,*End;
va_start(valist, num);
int (struct mesh*, void*,int) *thing; //Is this allowed?
switch(depth){
case 0:
Start = &(mesh->LV0); End = &(mesh->LVN);
break;
case 1:
Start = &(mesh->LE0); End = &(mesh->LEN);
break;
case 2:
Start = &(mesh->LF0); End = &(mesh->LFN);
break;
case 3:
Start = &(mesh->LC0); End = &(mesh->LCN);
break;
}//end switch.
/* access all the arguments assigned to valist */
for (ii = 0; ii < num; ii++) {
action[ii] = va_arg(valist, int (struct mesh*, void*,int)); //Is this allowed?
}//end "ii" loop.
for(ii = *Start;ii < *End;ii++){
for(jj = 0; jj < num;jj++){
thing = action[jj]; //Is this allowed?
mesh->ierr = thing(mesh,AppCtx,ii); CHKERRQ(mesh->ierr); //Here I attempt to call the functions.
}//end "jj" loop.
}//end "ii" loop.
/* clean memory reserved for valist */
va_end(valist);
return mesh->ierr;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
