返回void *的C ++ / C函数指针

我正在尝试调用一个带参数的函数, void(*)(void*, int, const char*) ,但我无法弄清楚如何将这些参数传递给函数。

例:

 void ptr(int); int function(int, int, void(*)(int)); 

我试图像这样调用函数:

 function(20, 20, ptr(20)); 

这可能吗?

你做错了一件事 – 你试图在调用’function’之前调用你的’ptr’函数。 你应该做的是只传递一个指向’ptr’的指针,并使用来自’function’的传递指针调用’ptr’,如下所示:

 void ptr(int x) { printf("from ptr [%d]\n", x); } int function(int a, int b , void (*func)(int) ) { printf( "from function a=[%d] b=[%d]\n", a, b ); func(a); // you must invoke function here return 123; } void main() { function( 10, 2, &ptr ); // or function( 20, 2, ptr ); } 

这使:

 from function a=[10] b=[2] from ptr [10] from function a=[20] b=[2] from ptr [20] 

这就是你想要的

对于

 function(20, 20, ptr(20)); 

工作 – 你必须要像:

 // 'ptr' must return sth (int for example) // if you want its ret val to be passed as arg to 'function' // this way you do not have to invoke 'ptr' from within 'function' int ptr(int); int function(int, int , int); 

通常的技巧是使用typedef进行签名:

  typedef void signature_t (void*, int, const char*); 

请注意,如果没有typedef ,语法就像一个函数声明。 它将signature_t声明为函数的typedef,因此在实践中你总是会使用指向signature_t指针。

然后你可以声明你的“高阶”function

  int function (int, int, signature_t*); 

另见此回复 。

函数调用的正确语法是:

 function(20,20, &ptr); 

如果您感到迷茫,请尝试一些教程 ,或者这样

除非我完全误解你的代码,否则你试图用一个参数传递函数指针

 function(20, 20, ptr(20)); 

这是不正确和非法的。 要将函数作为参数传递到另一个函数,您必须遵循以下语法

 function(20, 20, &ptr); or function(20, 20, ptr); 

尽管我会建议保留’&’以便于阅读

您不能将ptr(20)传递给此函数,因为您只能将指针传递给函数,而不能传递带参数的指针。 您可以阅读有关仿函数的内容,theu将帮助您解决此类问题。 或者另一种解决方案是将签名更改为

 int function(int, int, void(*)(void) ); 

并写function

 void ptr_wrap(void) {ptr(20);} 

所以你可以调用function(20, 20, ptr_wrap); 。 但是仿函数可以更优雅的方式解决这个问题。

ptr(20)ptr(20)的返回值,当你向它传递20时。 如果你想传递函数(而不是它的返回值),你应该只写function(20,20,ptr);