对函数指针的 C++ 引用

c++ reference to function pointer dynamically

本文关键字:C++ 引用 指针 函数      更新时间:2023-10-16

我有一个应用程序要完成以下任务

1.) UI application will send command code (integer value).
2.) DLL interface(in c++) will get that integer value and execute corresponding command function.
命令

名称和命令代码维护为

#define PING 50

将有 500 个命令,应用 SWITCH CASE 听起来不太好。 所以我决定在我的代码中实现函数指针,如下所示

   #include "stdafx.h"
    #include<iostream>
    #define PING 20
    using namespace std;
    //extern const int PING = 10; 
    void ping()
    { 
                    cout<<"ping command executed";
    }

    void get_status(void)
    {

    cout<<"Get_status called"<<endl;
    }
    class ToDoCommands
    {
            public:
                void getCommand( void (*CommandToCall)() );                         
    };

    void ToDoCommands::getCommand( void (*CommandToCall)())
    {

        void (*CommandToCall1)();
        CommandToCall1  = CommandToCall;
        CommandToCall1();
    }
    int main()
    {
            int code;
            ToDoCommands obj;
            cout<<"enter command code";
            cin>>code;  // if UI send 50 then Ping function get executed as #define PING 50
            obj.getCommand(ping);   // here m passing ping manually..
            //obj.getCommand(get_status);
                return 0;
    }

如何传递与命令代码对应的命令名称

obj.getCommand(ping); 

你快到了:将std::string std::map到函数指针,使用将字符串名称与相应函数指针配对的数据对其进行初始化,然后在运行时使用该映射根据传入的字符串参数选择正确的指针。

#include <iostream>
#include <string>
#include <map>
using namespace std;
void ping() {
    cout << "ping" << endl;
}
void test() {
    cout << "test" << endl;
}
int main() {
    map<string,void(*)()> m;
    m["ping"] = ping;
    m["test"] = test;
    // I am using hard-coded constants below.
    // In your case, strings will come from command line args
    m["test"]();
    m["ping"]();
    return 0;
}

链接到带有 std::map 的演示。

以下是无需map即可执行此操作的方法(由于线性搜索,它会变慢,但您可以通过按字母顺序排列名称并使用二叉搜索来修复它)。

#include <iostream>
#include <cstring>
using namespace std;
void ping() {
    cout << "ping" << endl;
}
void test() {
    cout << "test" << endl;
}
typedef void (*fptr_t)();
int main() {
    const fptr_t fptrs[] = {test, ping};
    const char *names[] = {"test", "ping"};
    const char *fname = "test";
    for (int i = 0 ; i != 2 ; i++) {
        if (!strcmp(fname, names[i])) {
            fptrs[i]();
            break;
        }
    }
    return 0;
}

链接到带有数组的演示。

声明一个函数指针数组。您将索引视为"代码"的地方。例如:

void foo(){
    printf("foon");
}
void bar(){
    printf("barn");
}
int main(void)
{
    void (*code_to_function[100])();
    int code;
    code_to_function[0] = foo;
    code_to_function[1] = bar;
    printf("Enter code: ");
    scanf("%d", &code);
    code_to_function[code]();
    return 0;
}

请注意,对于这个基本示例,输入 0 和 1 以外的整数代码将导致段错误。

我应该说@dasblinkenlight是对的,但如果你不想使用 std::map,你应该自己实现一个地图。这可能是错误的,而不是优化的方式,但如果你不想使用STL,似乎你应该自己实现它。

您可以使用 2 个具有相应索引的数组。其中一个是char *数组,另一个是函数指针。它们最好封装在名为MyMap之类的类中。

class MyMap {
  public:
    ...
    inline void add(char *name, (void (*ptr)(void)) ) {
      names_[currIndex_] = name; // Or stcpy
      ptrs_[currIndex_] = ptr;
      currIndex_++;
    }
    inline (void(*)(void)) get(char *name) {
      int foundIndex = -1;
      for (int i = 0; i < currIndex_; i++) {
        // Find matching index
      }
      if (foundIndex_ >= 0) {
        return ptrs_[foundIndex_];
      }
      return NULL;
    }
  private:
    int currIndex_;
    char *names_[10];
    (void (*ptrs_[10])(void));
};