How can I call a function, given its name as a string?

Showing Answers 1 - 10 of 10 Answers

hi2vino

  • Sep 13th, 2005
 

Just call the function names string as string() if the string function have no parameter if it have parameter then pass the corresponig value through the function call

  Was this answer useful?  Yes

Ilan

  • Apr 1st, 2007
 

this strongly depends on the language and library you're using. Some object oriented languages support a notion of reflection or introspection, where you can use a built in api to query objects, iterate over their methods and even invoke them. C++ has RTTI, java has java.lang.reflect or something simillar.

To implement simillar behavior in C, with gcc,

1. compile your program with  --export-dynamic on the gcc command line
2. link with -ldl (dynamic library handling, needed for dlopen and dlsym
3. call dlopen() with a null parameter, meaning you aren't loading symbols from a file but from the current executable
4. call dlsym() with the name of the function you'll be calling. Note that C++ modifies function names, so If you're trying this with C++, you'd have to either declare this function as extern "C", or figure out what name the function has after compiling. (On unix, you could run nm -s on the object file for this).
5. if dlsym() returns non-null, use the returned value as a function pointer to invoke your function.

Hi, This is a typical example of reflection. If you are using .NET then use reflection for this purpose. In this case you create an object of a particular  type and the invoke methods at run time by passing function name.

  Was this answer useful?  Yes

neeraj

  • Oct 26th, 2012
 

Ya it possible by using macro

Code
  1. #include<stdio.h>

  2. #define string sum1()

  3. int main(){

  4.  

  5. int k=string;

  6. printf("%d",k);

  7. getch();

  8. return 0;

  9.  

  10. }

  11. sum1()

  12. {

  13. int c=6;

  14. int d=7;

  15.  return(c+d);

  16. }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions