c - 在运行时将函数指针映射到特定数字

标签 c function mapping

我有一个问题,我什至可以开始着手解决,因为我不知道如何解决。

所以我们有一个代码

int test_handler() {
    printf("Test handler called\n");
    return 1;
}

// Test your implementation here
int main()
{
    register_irq_handler(30, &test_handler);
    do_interrupt(29); // no handler registered at this position, should return zero
    do_interrupt(30); // calls handler at position 30, expected output: Test handler called

    return 0;
}

我需要使这些函数 register_irq_handler、do_interrupt(29)。 但我不知道如何开始,我正在寻找一点帮助让我朝着正确的方向前进。

当我们没有全局变量来存储“连接”或者我遗漏了一些东西时,我如何存储 30 以指向此函数。

最佳答案

如果没有全局变量,您将无法做到这一点(为什么拥有全局变量会成为问题?)。

你可能需要这样的东西:

// array of 30 function pointers (all automatically initialized to NULL upon startup)
static int(*functionpointers[30])();    

void register_irq_handler(int no, int(*fp)())
{
  functionpointers[no] = fp;
}

int do_interrupt(int no)
{
  if (functionpointers[no] != NULL)
  {
    // is registered (!= NULL) call it
    return (*functionpointer[no])();
  }
  else
  {
    // not registered, just return 0
    return 0;
  }
}

免责声明

这是未经测试的非错误检查代码,仅供您引用。

关于c - 在运行时将函数指针映射到特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046036/

相关文章:

用C检查文件是否是纯文本

c - 制作 : flex: Command not found

function - R 中 `substitute` 的令人困惑的行为

database - 如何在 grails 域类中调整 Map 的约束/DB 映射

java - Java 中的插值 : Mapping a random number from one range to another

database - map : Does calculating distance between 2 points factor in altitude?

c - 编写一个C程序,使用指针将一维数组转换为二维数组

python - 从具有字符缓冲区的 DLL 为 C 函数创建 python 回调。

c++ - 为什么我的函数不能传递正确的值?

c++ - 为什么 int 不能用作返回类型的左值,而用户定义的类可以?