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
568 views
in Technique[技术] by (71.8m points)

c - Populating a va_list

Is there a way to create a va_list from scratch? I'm trying to call a function that takes a va_list as a parameter:

func(void **entry, int num_args, va_list args, char *key); 

...from a function that doesn't take a variable number of arguments. The only way I can think of is to create an intermediary function that takes varargs and then passing along its va_list, which is pretty stupid:

void stupid_func(void **entry, char *key, int num_args, ...) {
    va_list args;
    va_start(args, num_args);

    func(entry, num_args, args, key);

    va_end(args);
}

Is there a better way? I can't change func's signature.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a bad idea because the va_list abstraction is there to hide some grim compiler/architecture specific details regarding stack-pointers and what not. And it is pretty much bound to the function's scope once initialized. If you wind the stack and reference a previous frames va_args out of scope, things can go bad. You can pass them around but ...

expect bugs

See: http://lists.freebsd.org/pipermail/freebsd-amd64/2004-August/001946.html

Also checkout man(3) va_copy and friends for safer handling of va_args and passing them around.

IMHO the va_args stuff is not very neat. In the past I have dealt with this by initializing structures/opaque pointers on the heap then using pointer arithmetic to work the data. But this is a hack and depends on circumstances.


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

...