Re: [SLUG] [PIG] call a function without knowing its name in C

From: Sick Twist (thesicktwist@hotmail.com)
Date: Sun May 28 2006 - 10:32:30 EDT


>From: Paul M Foster <paulf@quillandmouse.com>
>Reply-To: slug@nks.net
>To: slug@nks.net
>Subject: Re: [SLUG] [PIG] call a function without knowing its name in C
>Date: Sun, 28 May 2006 03:42:36 -0400
>
>If I understand you correctly (and that's a 50/50 proposition), it seems
>like you could set up an array of function pointers, and then pass the
>array to function A. So that if function A sees keyword 'alfa', it calls
>the first member of the array. If it sees 'bravo', it calls the second
>member of the function pointer array. Etc. From the problem statement, it
>really only sounds like you need one level of indirection for the function
>calls.
>
>Does that help?
>
>--
>Paul M. Foster

That certainly sounds very close to what I would like but I still need to
figure out a way to convert the keyword read from the file to the
appropriate index number for the array of function pointers while only
needing to keep one list of keywords in the program:

/* ideally keep keywords in one place */
#DEFINE ANIMALS LION, TIGER, BEAR

enum {
ANIMALS,
TOTAL }

/* set up array of function pointers */
void (*func_ptr_array[TOTAL]) (void);

void func1 () {
...
/* call me for LION */
func_ptr_array[LION] = &func1;
...
}

void func2 () {
...
/* call me for TIGER */
func_ptr_array[TIGER] = &func2;
...
}

void func3 () {
...
/* call me for BEAR */
func_ptr_array[BEAR] = &func3;
...
}

void main () {
...
/* This is where I am stuck. How do I use ANIMALS and TOTAL
somehow for main to call the appriate function based on what it finds
in a file. I know I need some sort of string->integer lookup but I
just can't seem to figure it out:

animal_string = file_file_contents ();
???
func_ptr_array[animal_integer];
...
}

I thought about changing the #DEFINE to something like this

#DEFINE ANIMALS (ARG) LION ARG TIGER ARG BEAR

so that it could be passed a , from enum and "," from main. That way main
could use ANIMALS to initialize an array of strings for the lookup. Is there
a more simple way to achieve the same thing?

-Jonathon

-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 19:26:51 EDT