Re: pointer to function?
- From: John Bode <jfbode1029@xxxxxxxxx>
- Date: Tue, 13 Jan 2009 15:49:34 -0800 (PST)
On Jan 13, 3:03 pm, "Bill Cunningham" <nos...@xxxxxxxxxxxxx> wrote:
I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.
int (*pf) function (int,int);
Thanks.
I once worked on a system that had to process a number of files
generated by several Labview-driven instruments. Each instrument
generated two types of files: a calibration file and a data file, each
of which had to be treated differently.
So I wrote up a bunch of parsing and loading functions, then built a
lookup table of function pointers keyed by instrument and file type:
/**
* Lookup table type
*/
struct lut {
char *instrument;
char *extension;
int (*parser)(FILE *stream);
};
/**
* Parse function implementations
*/
int parseMSTData (FILE *stream) { /* parse MST data file */ }
int parseMSTCal (FILE *stream) { /* parse MST calibration file */ }
int parseGRAData (FILE *stream) { /* parse GRAPE data file */ }
int parseGRACal (FILE *stream) { /* parse GRAPE calibration data */ }
/**
* Lookup table data
*/
struct lut parserLookup[] =
{"MST", "DAT", parseMSTData},
{"MST", "CAL", parseMSTCal},
{"GRA", "DAT", parseGRAData},
{"GRA", "CAL", parseGRACal},
};
/**
* Main loop
*/
void ParseAllFiles(char **fileNames)
{
while (*fileNames)
{
char instrument[4], type[4];
int (*parser)(FILE *stream);
FILE *stream;
/**
* GetParser extracts the instrument and file
* type based on the file name, then retrieves
* the pointer to the right function from the
* lookup table; returns NULL if no matching
* function is found.
*/
parser = GetParser(char *fname);
if (parser)
{
FILE *stream = fopen (*fileNames, "r");
if (stream)
{
if (parser(stream))
/* load data */
fclose(stream);
}
}
fileNames++;
}
}
This allowed me to add new functions as new instruments came on line
without having to change the main processing code; all I had to do was
update the lookup table as I added new functions.
.
- References:
- pointer to function?
- From: Bill Cunningham
- pointer to function?
- Prev by Date: Re: Insert char at string
- Next by Date: Re: pointer to function?
- Previous by thread: Re: pointer to function?
- Next by thread: Re: pointer to function?
- Index(es):
Relevant Pages
|