Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a string to a function pointer in C? [duplicate]

Possible Duplicates:
call a function named in a string variable in c

I have certain functions.. say,

double fA1B1C1( .. ) {
         ...
}

double fA2B2C3( .. ) {
         ...
}

double (*fptr)( .. );

fptr myfunc;

These functions are already defined.

So when the user inputs the string "A2B2C2", it is got into a variable and converted to "fA2B2C2"

myfunc = formatted_string; // DOES NOT WORK

But the above syntax does not work. Even typecasting it does not work.

myfunc = (fptr) formatted_string // DOES NOT WORK

But if I hard code it as

myfunc = fA2B2C2 (or) myfunc = &fA2B2C2, it works pefectly.

Where am I going wrong?

EDIT::

I tried creating a hash table and a lookup function. Like

create_hashEntry(hashtable, string, formatted_string);
// string = "A1B1C1; formatted_string = "fA1B1C1"

then the look up function

myfunc lookup_func(char *string) {
       return(get_hashEntry(hahstable, string));
}

This also failed to work.


1 Answers

Actually, if the functions are extern, can you not do this with some super-duper evil dynamic loader trickery?

like image 154
Tom Anderson Avatar answered Feb 25 '26 01:02

Tom Anderson