Thread: calling functions from a file

  1. #1
    Join Date
    Feb 2003

    calling functions from a file

    ok, i was thinking that eventually i would probably need to implement a basic scripting language into my project. Now the question is, can one call a function whose name is in a string of characters without having to do a "if ( 'string' == functionname)"?

    the basic almost C style pseudocode for what i am looking at is:
    int callfunction(char* functionname, ...)//function name, and optional list of arguments read in
    (function*)(functionname)( ...,...);
    I figure it might be possible with function pointers, but i havent a clue on how to do this.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Well you can do something like this
    #include <iostream>
    #include <map>
    #include <string>
    #include <cmath>
    using namespace std;
    typedef double (*fn)(double);
    int main ( ) {
        map<string,fn> foo;
        foo["sin"] = sin;
        foo["cos"] = cos;
        cout << cos(0.1) << endl;
        cout << foo["cos"](0.1) << endl;
        return 0;
    But it only really works effectively if all the functions you want to call have the same prototype.

    If every function has a different prototype, then I think you have to go the if/else route, in order to get the right params to each function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM