Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...