在c语言中,函数同样有个地址,所以可以定义一个指针来指向一个函数,称为函数指针。
1. 函数指针的定义
在Linux内核中大量的使用了函数指针,例如:
struct bus_type {
...
int (*match)(struct device *dev, struct device_driver *drv);
...
};
在定义函数指针时,必须使用括号将'*'和指针名括起来,不然就是定义的一个函数只是它的返回值是一个指针而已。
2. 函数原型和函数指针的赋值
例如:
struct bus_type platform_bus_type = {
...
.match = platform_match,
...
};
再来看platform_match的定义:
static int platform_match(struct device *dev, struct device_driver *drv)
{
...
}
就是普通函数的定义。
3. 函数指针的调用
在driver_match_device中找到了对match的调用。
static inline int driver_match_device(struct device_driver *drv,
struct device *dev)
{
return drv->bus->match ? drv->bus->match(dev, drv) : 1;
}
采用了复合表达式,首先是判断match指针是否为NULL, 如果不为NULL,则调用该函数指针,否则直接返回1。
4. 函数指针作为函数参数
例如:
struct device *driver_find_device(struct device_driver *drv,
struct device *start, void *data,
int (*match)(struct device *dev, void *data))
{
...
}