Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

variadic functions - Variable arguments in C, how to get values with a generic type?

I'm trying to use C stdarg.h lib, with a generic type. The type int, is my generic type > to understand it, please, hold reading. So, my problem is:

I have a function that accept variable number of arguments. like

void function (int paramN, ...);

In my program, there are no way to know, which is the type of variable arguments, it can be a char, an array, an int, an short, an function point, etc... like

function (paramN, "Hey, I'm a string", 1, function_pint, array, -1); // -1 is a sentinel.

So, I think that, an int, is 32bits, in a x86(32bits) system, this will hold all address of memory. So, if I get all arguments with a int, it will not be a problem, for example, "Hey, I'm a string" the address of this string, fit normally in a 32bits variable, so, i need only to make a cast.

Im right?
Can I do it?
Note: I don't want to make my function like printf (this solution, don't fit in this case ok?)

Thanks for all answer.
And sorry for my bad english.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a void * (or a typed structure) for each parameter & use a structure with a "type" argument (an integer). A pointer / union to contain the actual value.

In other words, each parameter is passed with a pointer to a typed structure. Each instance of this typed structure contains a value. The type of this "value" is contained in this typed structure.

Better Example:

typedef struct  {
  int type;
  union {
    int int_value;
    double double_value;
    ...
  };
} Param;

void function(Param *p1, Param *p2, ...)

The latest example of such trick I ran into was DBus.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...