LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   accessing functions using strings in runtime (http://www.linuxquestions.org/questions/programming-9/accessing-functions-using-strings-in-runtime-321531/)

shyam_d_sundar 05-09-2005 01:49 AM

accessing functions using strings in runtime
 
hi,

I am designing a parser to read the input file for my code. In that, I use various commands and associate those commands with the relevant functions. Each time, i endup in adding a couple of lines like

if(strcmp(cmd,"clear")==0)
return clear();
else if(strcmp(cmd,"copy")==0)
return copy();


All the member functions in that class are of same name as the commands. So, i need to automate this process in order to avoid the above statements. In otherwords, i want some thing like below ( function pointers? )

for(int i=0;i<num_func;i++)
if(strcmp(cmd,func_name[i])==0)
return func[i]();

Please let me know.

Regards,
Shyam :study:

itsme86 05-10-2005 12:05 AM

I think the only way is to create a lookup table:
Code:

itsme@dreams:~/C$ cat funcptr.c
#include <stdio.h>
#include <string.h>

void a(void)
{
  puts("Inside a");
}

void b(void)
{
  puts("Inside b");
}

int main(void)
{
  struct
  {
    char *name;
    void (*func)(void);
  } list[] = {
              { "a", a },
              { "b", b },
              { NULL }
            };
  int i;
  char input[20];

  for(;;)  // Loop forever
  {
    printf("Enter a or b: ");
    fflush(stdout);

    fgets(input, sizeof(input), stdin);
    input[strlen(input) - 1] = '\0';

    for(i = 0;list[i].name;++i)  // Loop through list until NULL
      if(strcmp(list[i].name, input) == 0)
        list[i].func();
  }

  return 0;
}

Code:


itsme@dreams:~/C$ ./funcptr
Enter a or b: a
Inside a
Enter a or b: b
Inside b
Enter a or b: a
Inside a
Enter a or b:

jonaskoelker 05-17-2005 06:48 PM

even better yet, use a hash table.

mehuljv 05-18-2005 09:02 AM

hi shyam,
cant u use a macro ??
#define CALL_FUNC(name) name()
where name is the copy, clear, or any cmd which u read from the file (provided it is valid command - function in ur case).
So u just read the word from the file and just do CALL_FUNC(name) which will call ur function. ........
M sorry u cant do in this manner... preprocessor will remove ur macro before compilation.

Bye
Mehul


All times are GMT -5. The time now is 05:01 AM.