Re: Function Pointers
- From: Vimal Aravindashan <vimal@xxxxxxxxxxxxxx>
- Date: Mon, 21 Jan 2008 15:21:01 +0530
bwaichu@xxxxxxxxx wrote:
On Jan 20, 11:25 pm, Wang Jiaji <jiaji.w...@xxxxxxxxx> wrote:Well, one practical use of function pointers is, as Ben pointed out, its use as a callback functions. Arrays of function pointers are also useful. For example, you could have a set of signals:
In the machine code, the function's pointer and the function's name
are really the same thing, they're both the start point of a block of
instructions. The only difference is that, _in the C code_, you can't
reassign the function name to another block of instructions, while you
can with the function pointer. Unfortunately, your sample code missed
the only purpose of this candy syntax in C :p
I write assembly, so I'm used to returning out of all functions
(whether I set eax or not on x86 machines), and I am aware of calling
memory locations that contain functions from dlls, rather than
importing them.
But I struggle with practical usage and examples of function
pointers. I want to make sure I am getting the syntax right, and I
would like to know when I should use them. I think, the only place I
have seen them used is in libpcap.
int rts(void *data);
int cts(void *data);
int txd(void *data);
int rxd(void *data);
a typedef:
typedef int (*fp)(void *data);
an array of function pointers:
fp mysignals[] = {rts, cts, txd, rxd};
and use them as:
int err;
err = mysignals[0](NULL);
err = mysignals[2]((void *)"SOMETHING");
where the signals could be defined as:
int rts(void *data)
{
/* ignore data, do seomthing */
return 0;
}
int txd(void *data)
{
char *buf = (char *)data;
/* do something with buf */
return 0;
}
From what you had posted, I take it that you have got the syntax right. As for where you should use function pointers, well, that depends a lot on what you are trying to do.
Regards,
Vi
.
- Follow-Ups:
- Re: Function Pointers
- From: Richard Heathfield
- Re: Function Pointers
- References:
- Function Pointers
- From: bwaichu@xxxxxxxxx
- Re: Function Pointers
- From: Wang Jiaji
- Re: Function Pointers
- From: bwaichu@xxxxxxxxx
- Function Pointers
- Prev by Date: error while using fuction log2f()
- Next by Date: Re: error while using fuction log2f()
- Previous by thread: Re: Function Pointers
- Next by thread: Re: Function Pointers
- Index(es):
Relevant Pages
|