函数指针回调
Coddy 面向 Swift 开发者的 C 课程的第 38 课,共 48 课。
在 Swift 中,像 (Int) -> Int 这样的函数类型可以保存具名函数或闭包,而闭包可以捕获其周围环境中的变量;只有 @convention(c) 函数类型仅限于不捕获任何内容的代码。C 函数指针始终属于这种受限类型:它保存具有兼容签名且没有环境的函数地址,因此必须将状态作为额外参数显式传递。
函数指针具有兼容的签名。接收方必须调用调用方提供的回调。
Swift 示例
func twice(_ n: Int) -> Int { n * 2 }
let transform: (Int) -> Int = twice
print(transform(4))
Swift 输出:
8C 示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static int twice(int n){return n*2;}
int main(void) {
int (*transform)(int)=twice;printf("%d\n",transform(4));
return 0;
}
C 输出:
8挑战
简单实现 apply_sum(values,n,transform),将每个元素对应的 transform(value) 相加。输入最多包含 64 个整数。驱动程序会提供一个平方回调函数,还会使用另一个回调函数进行测试,以确保确实调用了该函数。输入为空时返回 0。
编辑未锁定的源文件和头文件。保持声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查数值范围,否则所有数值任务数据都足够小,不会溢出。只打印指定的输出;如果示例中提供了驱动程序,它会负责解析输入并输出结果。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int square(int n){return n*n;}
static int offset(int n){return n+7;}
int main(void){int probe[]={1,2};if(apply_sum(probe,2,offset)!=17)return 3;int values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;printf("%d\n",apply_sum(values,n,square));return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Swift 开发者的 C中的所有课
自己练习: C 在线编译器