views:

606

answers:

4

Possible Duplicates:
call a function named in a string variable in c
Dynamically invoking any function by passing function name as string

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.

+3  A: 

You can't turn strings into function pointers in C. You have to check the contents of the string to determine which function to use.

Tom Dalling
...and if you could, it would be a stupidly large security hole.
Rowland Shaw
+2  A: 

Read the duplicate, you'll find your answer.

I wanted to add, though, that this comes from a misunderstanding of how the program works.

These functions are at addresses in memory. Strings are not addresses. The names of functions, in code, are synonymous with their address. At runtime, having a string is really just having a pointer to some place in memory with characters. This has no relation to anything done at compile time, like function names.

Some languages include meta-data about the program, which means they do carry information about functions, their names, parameters, etc... at run time. C++ is not one of these languages.

This is why most answers will be a sort of simulation of this meta data: functions will be stored, and at run time you can use the string to peek into the table.

GMan
Please look at my edited post..
A: 

A string in C is a pointer to an array of chars, a function pointer is a pointer to some executable machine code. You can convert one to the other with a simple typecast, they are completly different things.

drhirsch
Actually the standard does not even guarantee the ability to perform the cast, AFAIK. (i.e. the pointers can be of different sizes)
EFraim
A: 

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

Tom Anderson