Advertisement
obernardovieira

Call function by string with params

Sep 15th, 2013
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. //the original code is not by me (but it is without params)
  2.  
  3. #include <cstdio>
  4. #include <cstdlib>
  5. #include <iostream>
  6.  
  7. /* These are your handler functions */
  8. void user_fn(char params[]) { printf("USER fn\n%s\n",params); }
  9. void pass_fn(char params[]) { printf("PASS fn\n%s\n",params); }
  10.  
  11. /* Stores a C string together with a function pointer */
  12. typedef struct fn_table_entry {
  13.     char *name;
  14.     void (*fn)(char params[]);
  15. } fn_table_entry_t;
  16.  
  17. /* These are the functions to call for each command */
  18. fn_table_entry_t fn_table[] = {{"USER", user_fn}, {"PASS", pass_fn}};
  19.  
  20. /* fn_lookup is a function that returns the pointer to the function for the given name.
  21.    Returns NULL if the function is not found or if the name is NULL. */
  22. void (*fn_lookup(const char *fn_name))(char params[]) {
  23.     int i;
  24.  
  25.     if (!fn_name) {
  26.         return NULL;
  27.     }
  28.     for (i = 0; i < sizeof(fn_table)/sizeof(fn_table[0]); ++i) {
  29.         if (!strcmp(fn_name, fn_table[i].name)) {
  30.             return fn_table[i].fn;
  31.         }
  32.     }
  33.     return NULL;
  34. }
  35.  
  36. int main() {
  37.     fn_lookup("USER")("char");
  38.     fn_lookup("PASS")("int");
  39.  
  40.     system("pause");
  41.     return 0;
  42. }
  43.  
  44. //example by user470379 without parameters
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement