In message <pa****************************@excite.com>
Jim Ford <jf*****@excite.com> wrote:
I wonder if the following is possible:
I would like to have a function with, say, three arguments. The
first two would be int, whereas the third one would be a pointer to a
generic function. By this I mean a function that can take any number of
arguments, of any type, and that can return anything, including void.
Is this allowed under ANSI C?
Not straightforwardly. You can leave the arguments unspecified, but that's
deprecated, and precludes any arguments actually being "narrow" types (ie
char, short, float). You have to specify a specific return type.
However, the standard says that you can store any function pointer value
in a function pointer of another type without loss - basically the same
guarantee as given for void * storing object pointers. So you could fudge it
thus, quite legally:
typedef void (*GenericFnPtr)(void); // any function ptr type would do
void jims_func(int a, int b, GenericFnPtr fn);
int myfunc(int a);
jims_func(1, 2, (GenericFnPtr) myfunc);
void jims_func(int a, int b, GenericFnPtr fn)
{
int n;
switch (a)
{
case 1: n = (((int (*)(int))p)(b);
break;
...
}
...
}
You will have to do all the icky casting, but maybe it could be tidied with
some more typedefs and/or macros. And obviously you'll have to know what
the actual type of the stored function actually is, so you can cast it back
to the correct type before use.
--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1223 503458
Cambridge, CB5 8HE, United Kingdom WWW:
http://www.tematic.com/