calling functions from a file

This is a discussion on calling functions from a file within the C++ Programming forums, part of the General Programming Boards category; ok, i was thinking that eventually i would probably need to implement a basic scripting language into my project. Now ...

  1. #1
    'AlHamdulillah
    Join Date
    Feb 2003
    Posts
    790

    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:
    Code:
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    Well you can do something like this
    Code:
    #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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 01:53 AM
  4. Replies: 3
    Last Post: 03-04-2005, 01: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21