Re: casting function pointers ?
Alfonso Morra wrote:
I have come accross some code where function pointers are being cast
from one type to another (admittedly, they all have the same return
type). eg. you may have func ptrs declr as ff:
typedef void (*vfptr)(void) ;
typedef void (*vfptr_i)(int) ;
typedef void (*vfptr_ii)(int, int ) ;
typedef void (*vfptr_iis)(int, int, char*) ;
the first declaration is used like a kind of base class functor in the
sense that sometimes, the other classes are cast "down" to it. In these
cases, the func args are determined at run time - typically, retrieved
from global variables etc.
This seems quite reckless. I have never seen anything like it before.
Has anyone come accros something like this before?
It's ugly, but far from reckless and sometimes necessary.
The Standard says that it's possible to convert a function
pointer from one type to another without harm, so the casts
using the types above are all right. The Standard also says,
though, that when a call is made the type of the function
pointer must agree with that of the called function, or else
you get undefined behavior. So,
void func_ii(int, int);
vfptr fp = (vfptr)func_ii; /* all is well */
fp(1, 2); /* compile-time error */
fp(); /* undefined behavior */
((vfptr_ii)fp)(1, 2); /* all is well */
You usually find this sort of thing in connection with a
table of function pointers accompanied by type codes of some
kind. They'll be used more or less like this
vfptr fp = table[i].funcptr;
switch (table[i].functype) {
case V:
fp();
break;
case I:
((vfptr_i)fp)(1);
break;
case II:
((vfptr_ii)fp)(1, 2);
break;
case IIS:
((vfptr_iis)fp)(1, 2, "three");
break;
...
default:
fprintf (stderr, "BUG: unknown type code %d\n",
table[i].functype);
die_horribly();
}
.... to allow the program to make a run-time choice among many
functions with different "signatures."
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx
.
Relevant Pages
- Re: casting function pointers ?
... typedef void; ... The Standard says that it's possible to convert a function ... pointer must agree with that of the called function, ... table of function pointers accompanied by type codes of some ... (comp.lang.c) - Re: change index between 0 and 1
... Warning for line above: ... function pointer array element with a pointer of a different type. ... typedef void (* fptr); ... (comp.lang.c) - Re: change index between 0 and 1
... Warning for line above: ... function pointer array element with a pointer of a different type. ... typedef void (* fptr); ... (comp.lang.c) - Re: change index between 0 and 1
... Warning for line above: ... function pointer array element with a pointer of a different type. ... typedef void (* fptr); ... (comp.lang.c) - Re: Another one for the list
... typedef void my_lib_void; ... Which standard (the standard for whichever version of the language the ... The Windows API is an infamous example of this too. ... But it is outside the realm of clc. ... (comp.lang.c) |
|