Home  >  Article  >  Backend Development  >  How to Call a C Function by Its Name Stored in a String?

How to Call a C Function by Its Name Stored in a String?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 11:04:30686browse

How to Call a C   Function by Its Name Stored in a String?

Calling a Function by Its Name (std::string) in C

In C , the question of calling a function by its name stored in a string has arisen. While a basic approach involving conditional statements is known, simpler alternatives have been sought.

Basic Approach

A straightforward method involves using a series of if-else statements to match the function name with the corresponding function pointer. This approach is illustrated below:

<code class="cpp">int function_1(int i, int j) { return i*j; }
int function_2(int i, int j) { return i/j; }

int callFunction(int i, int j, string function) {
    if(function == "function_1") {
        return function_1(i, j);
    } else if(function == "function_2") {
        return function_2(i, j);
    } ...
    return function_1(i, j);
}</code>

Proposed Alternative

The new approach aims to simplify the calling process by utilizing an std::map to map function names to function pointers. For functions with identical prototypes, this technique can provide a more concise solution:

<code class="cpp">#include <map>

typedef int (*FnPtr)(int, int);

int add(int i, int j) { return i+j; }
int sub(int i, int j) { return i-j; }

int main() {
    std::map<std::string, FnPtr> myMap;
    myMap["add"] = add;
    myMap["sub"] = sub;

    std::string s("add");
    int res = myMap[s](2,3);
    std::cout << res;
}</code>

This approach utilizes the myMap[s](2,3) syntax, which retrieves the function pointer mapped to the string s and invokes the corresponding function with the provided arguments. The example shown calculates and outputs 5 as the result of the "add" function call.

The above is the detailed content of How to Call a C Function by Its Name Stored in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn