Zulkarnine Mahmud
Zulkarnine Mahmud

Reputation: 113

dynamic function to call a function

Suppose someone has made individual functions in the following way separately for each person:

void John_age(void);
void Tom_age(void);
void Kate_age(void);
void Cathy_age(void);

....................

to determine their age.

Now I want to make such a function to call those functions by using just the person's names, like:

void age(char* NAME){...}

to call the specific function for that person "NAME".

void NAME_age(void);

is there any easy way to do that in C++ or C? I would really appreciate your help. Thanks.

The IDE i am using for a microcontrolles makes executable functions in the format void X_functionName(void); for every individual pin X. so I was looking for a more general approach to call them easily using functions like void customName(const char* X).

Upvotes: 1

Views: 509

Answers (7)

Mooing Duck
Mooing Duck

Reputation: 66981

Now that I know what your doing, I seriously recommend not doing that. But if you really really want to, polymorphism might be a more interesting way to go for C++, though of questionable effectiveness. Use a perl/python script to generate a header vaguely like this:

struct pin_type {
    virtual ~pin_type () {}
    virtual void name()=0; 
    virtual void age()=0; 
};

struct John_type : public pin_type {
    void name() {John_name();}
    void age() {John_age();}
};
John_type& John() {static John_type John_; return John_;}

struct Tom_type : public pin_type {
    void name() {Tom_name();}
    void age() {Tom_age();}
}
Tom_type & Tom() {static Tom_type Tom_; return Tom_;}

... thousands you say?

and then your normal code here:

pin* get_pin_by_name(const char* name) {
     //look up table of some sort, described by other answers
}

int main() {
    pin_type * pin = John(); //instant, and probably allows inlining next calls
    pin->age(); //same speed and size as function pointer
    pin->name(); //but we avoid multiple lookups
    pin = get_pin_by_name("Tom"); //runtime names can be ok too
    pin->name(); //calls Tom_name();
}

Upvotes: 2

user1095108
user1095108

Reputation: 14623

No one exploited the constexpr mechanism yet. Here it goes:

inline unsigned hash(char const* p)
{
  int h(0);

  for (; *p; ++p)
  {
    h = 31 * h + static_cast<unsigned char>(*p);
  }

  return h;
}

constexpr unsigned constHash(char const* in, uint const h)
{
  return *in ? constHash(in + 1, 31 * h + static_cast<unsigned char>(*in)) : h;
}

constexpr unsigned constHash(char const* in)
{
  return constHash(in, 0);
}

void process(char const* const name)
{
  switch (hash(name))
  {
    case constHash("John"):
      //...
      break;

    case constHash("Tom"):
      //...
      break;

    //...
    default:;
  }
}

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66981

It's pretty easy. Make a map of names to age functions.
typedefs make function pointers easier, and a static local map causes it to be initialized only once and then "cache" the results. Unordered maps are perfect for this sort of thing.

C++11:

void age(const std::string& NAME){
    static const std::unordered_map<std::string, void(*)()> age_lut = {
            {"John",John_age},
            {"Tom",Tom_age},
            {"Kate",Kate_age},
            {"Cathy",Cathy_age},
        };
    return age_lut.at(Name); //throws std::out_of_range if it doesn't exist
}

C: (Here I use a linear map instead of a hash like the C++, because I'm lazy)

typedef void(*)() get_age_func_type; 
typedef struct {
    const char* name;
    get_age_func_type func;
} age_lut_type;

age_lut_type age_lookup_table[] = {
            {"John",John_age},
            {"Tom",Tom_age},
            {"Kate",Kate_age},
            {"Cathy",Cathy_age},
        };
const unsigned age_lookup_table_size = 
        sizeof(age_lookup_table)/sizeof(age_lut_type);

bool age(char* NAME){
    bool found = false;
    //if you have a large number of functions, 
    //sort them in the initialization function, and 
    //use a binary search here instead of linear.
    for(int i=0; i<age_lookup_table_size ; ++i) {
        if (stricmp(age_lookup_table[i], NAME)==0) {
            age_lookup_table[i].func();
            found = true;
            break;
        }
    }
    return found;
}

All this code is off the top of my head and probably doesn't quite compile as is.

In reality, I highly recommend not having a function per person, use data instead. If absolutely needed, use a enumeration instead of a string to identify them.

Upvotes: 6

Prashant Kumar
Prashant Kumar

Reputation: 22679

You are describing something that is a commonplace feature in dynamic programming languages, something C and C++ are not.

Using std::unordered_map<void (*)(), std::string> as suggested by H2CO3 and Thomas Matthews is a good idea in C++.

With minimal overhead, you can use an if-else structure. This solution should work in C.

void age(char* NAME){
    void (*fp)(void);

    if      (strcmp(NAME, "John") == 0) { fp = John_age; }
    else if (strcmp(NAME, "Tom")  == 0) { fp = Tom_age; }
    /* ... additional cases ... */
    else { /* handle bad input */ }

    fp();  /* calls the appropriate age function */
}

Upvotes: 0

Wlodzislav K.
Wlodzislav K.

Reputation: 404

Simpliest but not scalable solution is something like this(in c++):

void age(std::string name) {
    if( name == "John" ) {
        John_age();
    }
    else if( name == "Tom" ) {
        Tom_age();
    }
    else if( name == "Kate" ) {
        Kate_age();
    }
    // and so on
}

Simple, scalable, but messy solution is to use macroses:

#define AGE(name) name##_age()

and call without quotes:

AGE(John);

Upvotes: 3

Thomas Matthews
Thomas Matthews

Reputation: 57749

In C++, you create a std::map of function pointers:

typedef void (*Age_Function_Pointer)(void); // Establish synonym for function syntax.

typedef std::map<std::string, Age_Function_Pointer> Lookup_Table;

unsigned int age(char const * name)
{
  static bool   table_is_initialized = false;
  Lookup_Table  name_func_map;
  if (!table_is_initialized)
  {
     name_func_map["Cathy"] = Cathy_age;
     name_func_map["Kate"]  = Kate_age;
     name_func_map["Tom"]   = Tom_age;
     name_func_map["John"]  = John_age;
  }
  std::string name_key = name;
  Lookup_Table::const_iterator iterator = name_func_map.find(name_key);
  unsigned int persons_age = 0U;
  if (iterator != name_func_map.end())
  {
     persons_age = (*(iterator.second))();
  }
  return persons_age;
}

Similarly in C you can create a look up table of function pointers:

struct Table_Entry_t
{
    char const *   name;
    Age_Function_Pointer p_func;
};

struct Table_Entry_t Age_Lookup_Table[] =
{
    { "Cathy", Cathy_age},
    { "Kate", Kate_age},
    { "Tom", Tom_age},
    { "John", John_age},
};
const unsigned int NUMBER_OF_ENTRIES =
    sizeof(Age_Lookup_Table) / sizeof(Age_Lookup_Table[0]);

unsigned int age(char const * person_name)
{
   unsigned int person_age = 0;
   unsigned int i = 0;
   for (i = 0; i < NUMBER_OF_ENTRIES; ++i)
   {
      if (strcmp(person_name, Age_Lookup_Table[i]) == 0)
      {
        person_age = (Age_Lookup_Table[i].p_func)();
        break;
      }
   }
   return person_age;
}

Upvotes: 3

user529758
user529758

Reputation:

is there any easy way to do that in C++ or C

In C++, no, due to the horrible name mangling (unless you make an std::unordered_map<void (*)(), std::string> of all the possible functions). But in C, you can do this:

void *hndl = dlopen(NULL, RTLD_NOW); // or dlopen(RTLD_DEFAULT, RTLD_NOW)
void (*fptr)(void) = dlsym(hndl, "func_name");
fptr();

Upvotes: 2

Related Questions