简体   繁体   English

C:在传递给它的函数中传递一个函数指针

[英]C: Passing a function pointer in a function it is passed to

I'm trying to write a mapping function that takes a function pointer, and passes it to another function, but gcc is yelling at me. 我正在尝试编写一个带有函数指针的映射函数,并将其传递给另一个函数,但是gcc对我大吼大叫。

Here is an idea of what I'm trying to do. 这是我想要做的事情的想法。

void map(T thing, void apply(int a, int b, void *cl), void *cl);

void function(T thing, void apply(int a, int b, void *cl), void * cl)
{

   for(int i = 0; i < 10; i++)
   {

      map(thing, apply, cl);

   }

}

gcc's complaint: gcc的抱怨:

warning: passing argument 2 of 'map' from incompatible pointer type 警告:从不兼容的指针类型传递'map'的参数2

Any ideas? 有任何想法吗?

In order to help with this problem we'd need to see the declaration / signature of the map function. 为了帮助解决这个问题,我们需要查看map函数的声明/签名。 Almost certainly there is a slight difference in the function signature. 几乎可以肯定,功能签名略有不同。 The easiest way to resolve this is to typedef out a function pointer type and use it in both functions. 解决这个问题的最简单方法是输入一个函数指针类型并在两个函数中使用它。

typedef void (*apply)(int,int,void*);

You can't pass functions around. 你不能传递函数。 You need to pass pointers to functions instead. 您需要将指针传递给函数。

void map(T thing, void (*apply)(int a, int b, void *cl), void *cl);
void function(T thing, void (*apply)(int a, int b, void *cl), void * cl)
{
    /* ... */
    map(thing, apply, cl);
    /* .... */
}

It's just complaining that the function pointer type expected by map 's second argument is different from that of apply . 它只是抱怨map的第二个参数所期望的函数指针类型与apply不同。 If you either change that type, or (if safe) cast, then it'll be fine. 如果你要么改变那种类型,要么(如果安全)施放,那么它会没事的。

It works for me with gcc 4.3.3 and -Wall . 它适用于gcc 4.3.3和-Wall

While I think all versions of C that ever existed rewrote function "value" parameters to be pointers, you could use a more traditional declaration: 虽然我认为所有存在的C版本都重写了函数“value”参数作为指针,但您可以使用更传统的声明:

void function(T thing, void (*f)(int a, int b, void *cl), void * cl)

But, like I said, your example works fine for me, unchanged except for typedef int T , and map(1, ...) 但是,就像我说的,你的例子对我来说没问题,除了typedef int Tmap(1, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM