c 语言函数指针用法

在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))
{
	...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值