Search code examples
cstringfunctionintrospection

Pass a string containing a function name and its arguments to another function.


I would like to pass a string to a function in C in which the function will parse out a function name, the arguments for the function, and its datatypes, and then call the function for me. What is the best approach?


Solution

  • If you want to write a function with a format string and variable arguments like:

    int function(const char* strFormat, ... )
    {
      //parse out the format using regex or something
      //then store the data into the variable aruments
      //or create a string concatenating everything
    }
    

    like, say printf, sprintf, or scanf does,

    then the best thing for you to do is look at some good tutorials.

    http://msdn.microsoft.com/en-us/library/fxhdxye9(v=vs.80).aspx

    http://www.cprogramming.com/tutorial/c/lesson17.html

    If you are wanting to actually pass a function name for the function to call, along with its arguments, you either need to implement some form of reflection or introspection in your c code, a really complex switch statement which calls the functions for you based upon the string value, or write some complex macros to act as a sort of a secondary compiler.

    glib's gobject is an excellent example of introspection in c. http://developer.gnome.org/gobject/stable/

    something simple without introspection may be:

    void* function (const char* strFunctionName, ... )
    {
      if(!strcmp(strFunctionName, "functionA"))
      {
        //use va_list to parse out the arguments for the function.
        functionA(//each of the arguments from va_list);
      }
      else if(!strcmp(strFunctionName, "functionB"))
      {
        //use va_list to parse out the arguments for the function.
        functionB(//args from va_list);
      }
      ...
    }
    

    If you have something more specific in mind, please specify in your question.