问题描述
我对如何实现以下内容感到有些困惑。我想要一个函数func2
,返回一个函数,该函数使用指定的参数调用func1
:
int func1(int x,int y,int z,int type){
// Calculations
}
int ((*func2)(int x,int z))(int type){
// Return a pointer to func1 that with get x,y,z as parameters
// when called later,with type = type being fixed
}
使用:
my_func = func2(3);
printf("result = %d\n",my_func(1,2,3));
解决方法
要使其正常工作,您需要一个叫做 closure 的东西,它基本上是一条记录,其中函数和类型为字段。下面是一个例子来说明这个想法。在真实程序中,您还需要检查malloc不返回NULL,并释放内存。
#include <stdio.h>
#include <stdlib.h>
typedef struct ClosureDesc *Closure;
struct ClosureDesc {
int type;
int (*function)(Closure c,int x,int y,int z);
};
int func1(Closure c,int z)
{
return c->type;
}
Closure func2(int type)
{
Closure c;
c = malloc(sizeof *c);
c->type = type;
c->function = func1;
return c;
}
int main(void)
{
Closure my_func;
my_func = func2(3);
printf("result = %d\n",my_func->function(my_func,1,2,3));
return 0;
}
,
函数指针语法有点混乱,但是您可以使对函数本身的类型定义更容易。然后,您可以使用“常规”指针语法。
typedef int func(int,int,int);
int func1(int x,int z){
// Calculations
return 1;
}
int func2(int x,int z){
// Calculations
return 2;
}
int func3(int x,int z){
// Calculations
return 3;
}
func *selectfunc(int type)
{
func *f = NULL;
switch(type)
{
case 1:
f = func1;
break;
case 2:
f = func2;
break;
case 3:
f = func3;
break;
}
return f;
}
int main(void)
{
int type = rand()%3;
printf("%d",selectfunc(type)(1,3));
}
或
func *fptr = selectfunc(2);
fptr(1,3);
,
我想这就是你要去的地方
git fetch origin
git checkout origin/gh-pages -b gh-pages
如果您编写int func1( int x,int z )
{
...
}
/**
* func2 takes an integer parameter and returns a
* pointer to a function that takes 3 integer
* parameters and returns int
*/
int (*func2(int type))(int,int)
{
/**
* This example is based on what you wrote in your
* question. Regardless of how you actually select
* which function to return based on the input,the
* return statement will be the same.
*/
switch ( type )
{
case 3:
return func1;
break;
default:
break;
}
return NULL;
}
int main( void )
{
int (*my_func)(int,int);
...
my_func = func2( 3 );
if ( my_func )
printf( "result = %d\n",my_func( 1,3 ) );
...
}
使其永远无法返回func2
,并且您希望您的同事向您扔东西,则可以省去{{1 }}变量,然后编写
NULL
我不会推荐它,除非您喜欢代码审查中的粗鲁注释。