D.Bear
D.Bear

Reputation: 3

c how to evaluate function pointer using function name

This is my snippet:

typedef void (*FUNCPT)(void);

void func1();

int main(){
    FUNCPT fpt1;
    char *s = "func1";

    return 0;
}

I can evaluate fpt1 like this :

fpt1 = func1;

But there is some reason that I must use function name to evaluate function pointer, I expect to get same value by something like this:

fpt1 = (FUNCPT)s;

How can I achive this?

Upvotes: 0

Views: 184

Answers (2)

4386427
4386427

Reputation: 44274

I don't think there is any portable way to do that. I think you need to write your own code for that. For instance a look-up table like:

#include <stdio.h>

void func1() {printf("func1\n");}
void func2() {printf("func2\n");}
void func3() {printf("func3\n");}

typedef void (*FUNCPT)(void);

typedef struct lookup
{
    FUNCPT f;
    char name[32];
} lookup;

lookup lookup_table[] = {
    {func1, "func1"},
    {func2, "func2"},
    {func3, "func3"},
};

FUNCPT getFuncByName(char* str)
{
    int i;

    for (i=0; i < (sizeof(lookup_table)/sizeof(lookup)); ++i)
    {
        if (strcmp(str, lookup_table[i].name) == 0) return lookup_table[i].f;
    }
    return NULL;
}
int main(){
    FUNCPT fpt = getFuncByName("func2");

    if (fpt) fpt();

    return 0;
}

Upvotes: 1

tofro
tofro

Reputation: 6063

The only way to evaluate a function name to a function pointer (without referring to a fixed table of symbols vs. names in your own code) is using shared libraries and dlopen(), dlsym() and the likes in the Linux/Unix world and the appropriate equivalents in the Windows world.

  1. Put the functions you want to resolve into a shared library
  2. Open that shared library from your program using dlopen
  3. Find the symbol by name using dlsym
  4. Cast that returned address into a proper function pointer and call it

This is, however, more an OS than a C question. Without stating your platform, further help is not possible.

Upvotes: 2

Related Questions