c语言与函数式编程1(wrapper function)

一、c语言与函数式编程模式(funcitonal programming)

1)c语言通过函数指针(函数指针可以作为参数,也可以作为返回值)对funcitonal programming提供一定的支持

2)但又远不够强大,本身不支持闭包,嵌套定义等,远未达到funcitonal programming中first class function(high order function)的境界


二、c语言标准中对函数指针的阐释
1)函数指针可以进行类型转换,也就是从一种函数指针类型转换成另一种

2)但不支持函数指针非兼容类型(两个函数指针具有不同的返回值等)的调用,可能会破坏栈


三、举例说明(wrapper function为例)
1)TaskCreate创建一个线程,入口函数为entryPoint,由于entryPoint的函数类型和pthread_create中的函数类型不同
2)若直接进行转换可能会引入上文提到的风险
3) 所以封装一 entry_wrapper函数,同时将entryPoint作为线程入口函数参数传递给pthread_create


源码如下:
void *entry_wrapper (void (*entryPoint)(void))//ljc define a wrapper funciton,(tycast different signature function pointer is ok,but call it use another type may corrupt stack)
{
  //entryPoint();
entryPoint();
return NULL;

}


int TaskCreate(UINT8 sName[], UINT32 dStackSize, void (*entryPoint)(void),INT32 dPriority, void *pPara, UINT32 *pTaskId)
{
  
  pthread_t thread;
pthread_attr_t attr;
struct sched_param param_sched;


param_sched.sched_priority=map_range_Osp(dPriority, 0, 255, 1, 99);

if(dStackSize<PTHREAD_STACK_MIN)
dStackSize=PTHREAD_STACK_MIN;
if(pthread_attr_init(&attr)!=0)
return -1;
printf(" %s %d %d\n",__FUNCTION__,__LINE__,PTHREAD_STACK_MIN);
printf("  %d\n",pthread_attr_setstacksize(&attr,(size_t)dStackSize));
printf("  %d\n",pthread_attr_setschedpolicy(&attr,SCHED_RR));
printf("  %d\n",pthread_attr_setschedparam(&attr,&param_sched));
if((pthread_attr_setstacksize(&attr,(size_t)dStackSize)!=0)||(pthread_attr_setschedpolicy(&attr,SCHED_RR)!=0)||(pthread_attr_setschedparam(&attr,&param_sched)!=0))
return -1;
printf(" %s %d\n",__FUNCTION__,__LINE__);
// if(pthread_create(&thread, &attr,(void *(*) (void *))entryPoint,pPara)!=0)//ljc when startroutine over,it will auto call pthread_exit;take startroutine's return value as it's exit status
  if(pthread_create(&thread, &attr,(void *(*) (void *))entry_wrapper,entryPoint)!=0)
  return -1;
if( pthread_attr_destroy(&attr)!=0)
return -1;
  if(pTaskId)
*pTaskId=(UINT32)thread;
return 0;
}



四、高阶函数(high order function)
1)entry_wrapper本身有局限,若TaskCreate的定义如下:
int TaskCreate(UINT8 sName[], UINT32 dStackSize, void (*entryPoint)(void*),INT32 dPriority, void *pPara, UINT32 *pTaskId)

也就是pPara不为空,那例子中pPara就不能用来传递entryPoint,那上文中的entry_wrapper就无法正常工作了


2)解决此问题的策略,可用高阶函数(接收一个函数作为参数,并返回一个新的函数指针),高阶函数的定义需满足下述条件之一
函数作为另一个函数的input,也就是参数
函数作为另一个函数的output,也就是返回值
高阶函数的 lua代码示例:
    function newCounter ()
      local i = 0
      return function ()   -- anonymous function
               i = i + 1
               return i
             end
    end

3)高阶函数的实现,由于c语言本身的局限,实现起来相对复杂,后续再进一步说明
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值