pr********@gmail.com wrote:
Hi,
I am a newbie to this group. I have a problem in handling the variable
arguments passed to a function. My requirement is like this.
I have 2 functions say,
void funcX(int i, int j);
void funcY(int i, int j,char *name);
Now I want to register this function some how and store the variable
arguments ( and store defualt values) for future use
RegisterFunc(funcX,10,20);
RegisterFunc(funcY,50,60,"MyName");
( Here I want to know how I can register and store the variable
arguments and function pointers, so that it can be used at a later
point to invoke the same)
Now at a later point I want to evoke these store functions in a
sequential order.
CallFuncs()
{
//Invoke funcX with values registered here;
//Invoke funcY with values registered here;
}
I was trying to use va_args with C and somehow i was not able to be
successful. If anybody have a better suggestion/design on how to do it,
I really don't think you can do this using varags functions.
Instead why not something like this:
/* generic implementation */
/*
* Does not support unregistering as that's
* a bit harder: We need to make sure nothing
* gets deleted in our list while we're walking
* it in call_funcs.
*/
#include <stdlib.h>
struct func{
struct func *next;
void (*f)(void *data);
void *data;
};
static struct func *first;
int register_func(void (*f)(void *data), void *data){
struct func *func;
func = malloc(sizeof *func);
if(func == NULL){
return 0;
}
/*
* Initialize: notice that we don't copy data
* and leave it as responsability of the caller
* to hand us data that persists until the last
* call to call_funcs
*/
func->f=f;
func->data=data;
/*
* Prepend to the list: functions will be
* called in reverse order from registration
*/
func->next=first;
first=func;
return 1;
}
void call_funcs(void){
struct func *func;
for(func = first; func != NULL; func = func->next) {
func->f(func->data);
}
}
/* interface header */
int register_func(void (*f)(void *data), void *data);
void call_funcs(void);
/* Now use this in our program */
/* missing #include "func.h" to post a single file to clc */
#include <stdio.h>
struct argX{
int a;
int b;
};
struct argY{
int a;
int b;
char *name;
};
void funcX(void *data){
struct argX *X=data;
printf("funcX with a=%d, b=%d\n",X->a,X->b);
}
void funcY(void *data){
struct argY *Y=data;
printf("funcY with a=%d, b=%d, name=%s\n",Y->a,Y->b,Y->name);
}
int main (void) {
struct argX X1={1,2};
struct argX X2={3,4};
struct argY Y ={5,6,"hello"};
register_func(funcX,&X1);
register_func(funcY,&Y);
register_func(funcX,&X2);
call_funcs();
return 0;
}
Tobias