An example of an API that you can't do with C stdargs

May 21, 2010

(This is a followup to yesterday's entry.)

Update: I'm actually completely wrong about this, both in practice on x86 machines with gcc and, I believe, in standards-compliant theory, as brought to my attention by nothings in comments.

One general class of impossible-in-C varargs APIs is heavily polymorphic dispatch APIs where you need to dispatch to one of several different varargs functions that have different constant arguments. Here is a gratuitous (and probably bad) API example:

void maybeLog(int what, int where, ...)

This acts as a master function that determines whether or not something gets logged to a particular output destination and then logs it if it is. Possible output destinations include standard output, some file descriptor (including standard error), or syslog, and in each case the remaining arguments are the arguments that you would pass to the respective normal output function (printf(), fprintf(), and syslog()) if you were calling it directly.

This API cannot be implemented in (standard) C because each of the output functions you want has different fixed arguments, and you cannot extract and remove the fixed arguments from the va_list in order to call one of the v* versions with the correct arguments. The only possibly prototype for this is:

void maybeLog(int what, int where, FILE *fp, int priority, char *format, ...)

(maybeLog can then call the appropriate v* function with its required fixed arguments plus the va_list; it ignores fixed arguments not needed by the output function.)

In other words, you're supplying the union of all fixed arguments potentially needed by any output function. This has several drawbacks, including the lack of extensibility if you want to add another output destination that needs a new set of fixed arguments.

(I believe that the usual approach to doing this kind of API in C is to use a preprocessor macro. This has its own problems.)

Written on 21 May 2010.
« The limitations of C's varargs support
Why I'm wrong about what sort of APIs C's stdargs allows »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri May 21 01:19:24 2010
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.