#include <stdio.h>
int a = 0;
void (*fancp)();
void test(void(*fanc)())
{
a = 1;
fancp = fanc;//注册
}
void hello()
{
printf("hello\n");
}
int main(int argc, char** argv)
{
test(hello);//该行代码在其他c文件中实现才有意义
printf("%x\n", fancp);//打印fancp的地址,在使用中可以判断fancp的值来确定是否已经注册,fancp==0为没有注册
(*fancp)();
return 0;
int a = 0;
void (*fancp)();
void test(void(*fanc)())
{
a = 1;
fancp = fanc;//注册
}
void hello()
{
printf("hello\n");
}
int main(int argc, char** argv)
{
test(hello);//该行代码在其他c文件中实现才有意义
printf("%x\n", fancp);//打印fancp的地址,在使用中可以判断fancp的值来确定是否已经注册,fancp==0为没有注册
(*fancp)();
return 0;
}
这种实现机制和java 的接口(常见的setListener())是很像的。
C语言函数指针示例
本文通过一个C语言函数指针的例子展示了如何通过函数指针实现类似Java接口的功能,如设置监听器。代码示例中定义了一个全局变量a,并声明了一个指向无参数且返回类型为void的函数指针fancp。通过test函数注册了hello函数,并在main函数中调用。
1293

被折叠的 条评论
为什么被折叠?



