我有一个问题,我什至可以开始着手解决,因为我不知道如何解决。
所以我们有一个代码
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/