Casting function ptrs

Walter Murray walter at hpcllz2.HP.COM
Sat May 21 03:25:42 AEST 1988


Dave Hammond writes:

>Given a list of varying typed functions, their names and addresses:
>And a routine which is passed a function name in order to lookup and return
>its associated address: 
>How does one declare the lookup function, the return address variable and
>call the returned function, while properly casting the function return value?
>I'm doing it like so:
[all examples deleted]
>Yes? No? Gonna blow up on me at some point ?

Dave, if I understand you right, when you call lookup_func("foo"),
you know what type foo() is going to return, and you just need to look
up its address.  If that's the case, I think the following is what
you want.  It's close to what you had, and lint likes it. Other things
will work, but I think the following has the virtue of being strictly
conforming per the dpANS.

#include <stdio.h>
#include <string.h>
struct funcs {char *name; void (*func)();};
char *foo() {return "It worked!";};
struct funcs f = {"foo",(void(*)())foo};
void (*lookup_func(name))()
   char *name;
{
   if (!strcmp (name, f.name)) return f.func;
   else return 0;
}
void (*func)();
char *retp;
main ()
{
   if ((func = lookup_func ("foo")) != 0) 
      if ((retp = ((char*(*)())func)()) != 0)
	 (void) printf ("retp = %s\n",retp);
   return 0;
}

Walter Murray

All opinions expressed are my own.



More information about the Comp.lang.c mailing list