Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
If I have a char * variable pointing to the name of a function ...
If I have a char * variable pointing to the name of a function, how can I call that function? Code like
extern int func(int, int);
char *funcname = "func";
int r = (*funcname)(1, 2);
or
r = (*(int (*)(int, int))funcname)(1, 2);
doesn't seem to work.
✍: Guest
By the time a program is running, information about the names of its functions and variables (the ``symbol table'') is no longer needed, and may therefore not be available. The most straightforward thing to do, therefore, is to maintain that information yourself, with a correspondence table of names and function pointers:
int one_func(), two_func();
int red_func(), blue_func();
struct { char *name; int (*funcptr)(); } symtab[] = {
"one_func", one_func,
"two_func", two_func,
"red_func", red_func,
"blue_func", blue_func,
};
Then, search the table for the name, and call via the associated function pointer, with code like this:
#include <stddef.h>
int (*findfunc(char *name))()
{
int i;
for(i = 0; i < sizeof(symtab) / sizeof(symtab[0]); i++) {
if(strcmp(name, symtab[i].name) == 0)
return symtab[i].funcptr;
}
return NULL;
}
...
char *funcname = "one_func";
int (*funcp)() = findfunc(funcname);
if(funcp != NULL)
(*funcp)();
The callable functions should all have compatible argument and return types. (Ideally, the function pointers would also specify the argument types.)
It is sometimes possible for a program to read its own symbol table if it is still present, but it must first be able to find its own executable , and it must know how to interpret the symbol table (some Unix C libraries provide an nlist function for this purpose).
2015-02-20, 1519👍, 0💬
Popular Posts:
Explain all parts of a deployment diagram? Package: It logically groups element of a UML model. Node...
How can a servlet refresh automatically if some new data has entered the database? You can use a cli...
Can one execute dynamic SQL from Forms? Yes, use the FORMS_DDL built-in or call the DBMS_SQL databas...
How do you locate the first X in a string txt? A) txt.find('X'); B) txt.locate('X'); C) txt.indexOf(...
What is the benefit of using an enum rather than a #define constant? The use of an enumeration const...