I would like to have a function that takes in parameters of generic types, which is possible with variadic functions but I am looking for some suggestions/help.
Basically, the function could accept any primitive types (int, double, char* etc) and certain local structs/pointers to it. I did the following where I hardcode the ENUM values for primitive types and structs.
I came up with a following solution but it doesn't look neat to me at least for the primitive types which I'm using inside ENUM. I see vfprintf
could be used inside a variadic function with parameter being const char *format, ...
but how do I handle structs and multiple parameters with this approach?
enum types {LONG, INT, FLOAT, DOUBLE, CHAR, STRUCT};
typedef struct
{
int size;
char data[64];
} Pkt;
void bar(int len, va_list ap)
{
Pkt pkt = va_arg(ap, Pkt);
printf ("[Bar] packet: %d, %s\n", pkt.size, pkt.data);
}
void foo(int len, ...)
{
char *str;
double val;
int intVal;
va_list ap;
Pkt pkt;
va_start(ap, len);
bar(len, ap);
va_end(ap);
va_start(ap, len);
for (int i=0; i<len; i++)
{
int type = va_arg(ap, enum types);
switch(type)
{
case CHAR:
str = va_arg(ap, char*);
printf ("CHAR: %s\n", str);
break;
case DOUBLE:
val = va_arg(ap, double);
printf ("DOUBLE: %f\n", val);
break;
case INT:
intVal = va_arg(ap, int);
printf ("INT: %d\n", intVal);
break;
case STRUCT:
pkt = va_arg(ap, Pkt);
printf ("STRUCT: %d, %s\n", pkt.size, pkt.data);
break;
default:
break;
}
}
va_end(ap);
}
int main()
{
Pkt pkt = {.size = 50, .data = {"Hello"}};
char *str = "World";
foo(2, STRUCT, pkt, CHAR, str);
return 0;
}