函数指针用法示例

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2、void MyTask(void*p_arg)
{
//用户代码
}
typedef (*OS_TASK_PTR)(void *p_arg);
OS_TASK_PTR p_Func ;定义一个函数指针变量p_Func;
p_Func = MyTask;
等价于: void(*p_Func)(void *p_arg) ;
p_Func = MyTask;
函数指针在操作系统内核源码中的使用较多,所以对于函数指针变量的定义形式,赋值形式及调用形式一定要清晰;

3、其他形式

struct t_String{
    uint8_t *string;
    uint32_t size;
    uint32_t length;
};
typedef struct t_String   T_String;

typedef struct {
    char *command;
    T_String *(*handler)(char *msg, u16 len);  //函数指针
}T, *P;

static T commandhandlers[] =
    {
        {"A", 
         A_Handler},
        {"B", 
         B_Handler},
        {NULL,
         NULL}   };

P FUNC1(const char *cmd)
{
 P ptmp = commandhandlers;
    while (ptmp->command != NULL)
 {
        if (*(ptmp->command) == *cmd) 
        //输入字符 是否等于数组列举的 字符
        {
            return ptmp;
        }
        ptmp++;
    }
    return NULL;
   
}

void FUNC2(const char *cmd)
{
        P handler = FUNC1((str + 1));
       if (handler != NULL)
       {
           T_String *value_Return = handler->handler(str + 2, 2);
        }
}

4、用法示例


```c
  typedef struct
	{
		u8* cmd;
		u8 *(*handler)(u8*msg,u16 len);
	} VAR,*PTR_VAR;
	
	// 其中 PTR_VAR 等效于  VAR*
		   
    //定义数组
    VAR  array[]= 
	{
	   {"A",
	   forA_HandlerFunc};
	   ...
	   {"Z",
	   forZ_HandlerFunc};
	   {NULL,NULL
	   }
	};
	
	PTR_VAR Func1(u8*cmd)
	{
		PTR_VAR ptmp = array //将数组首地址给该指针
		while(ptmp->cmd != NULL)
		{
			if(*(ptmp->cmd) == *cmd)
			{
				return ptmp;
			}
			ptmp++;
		}
		return NULL;
	}
	
	void main()
	{   
	    if(*(str+1)大于A小于Z)
		{
			PTR_VAR ptmp2 = Func1(str+1);
			if(ptmp2 != NULL)
			{
				ptmp2->handler(str+2,len);
				
			}
		}			
		
	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SUR0608

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值