【问题标题】:Can we call functions using function pointer in C?我们可以在 C 中使用函数指针调用函数吗?
【发布时间】:2010-09-20 03:15:40
【问题描述】:

我们可以使用函数指针调用函数吗?如果是怎么办?

【问题讨论】:

    标签: c pointers function-pointers


    【解决方案1】:

    是的。简单的例子:

    
    // Functions that will be executed via pointer.
    int add(int i, int j) { return i+j; }
    int subtract(int i, int j) {return i-j; }
    
    // Enum selects one of the functions
    typedef enum {
      ADD,
      SUBTRACT
    } OP;
    
    // Calculate the sum or difference of two ints.
    int math(int i, int j, OP op)
    {
       int (*func)(int i, int j);    // Function pointer.
    
       // Set the function pointer based on the specified operation.
       switch (op)
       {
       case ADD:       func = add;       break;
       case SUBTRACT:  func = subtract;  break;
       default:
            // Handle error
       }
    
       return (*func)(i, j);  // Call the selected function.
    }
    
    

    【讨论】:

    • Greg:感谢您的高亮编辑——每天学习新东西!
    【解决方案2】:

    是的。这是带有示例的good tutorial

    【讨论】:

      【解决方案3】:

      是的,你可以。

      【讨论】:

      • 同意 +1。哇,希望他们都那么容易。
      【解决方案4】:

      是的。一个例子:

      代码之前...

      typedef int ( _stdcall *FilterTypeTranslatorType ) ( int TypeOfImportRecord, PMA 类型 *PMA ); FilterTypeTranslatorType FilterTypeTranslator = {NULL};

      现在在代码中...

      PMA类型 *PMA; 处理 hFilterDll; // 假设 DLL 已加载 // 现在找到地址... ... FilterTypeTranslator[TheGroup] = ( FilterTypeTranslatorType ) GetProcAddress( hFilterDll, "FilterTypeTranslator" ); ... // 现在调用它 FilterTypeTranslator(1,PMA); ...

      【讨论】:

        猜你喜欢
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-22
        • 1970-01-01
        相关资源
        最近更新 更多