5

I have the following function

static void p (){

}

I want to pass a function pointer to p into function x.

void x(void * ptr){

}

I am trying the following, and it is not working.

...
x(ptr);

Note x and p are in different classes. I am getting the following compiling error.

invalid conversion from 'void (*)()' to 'void*' [-fpermissive]
Sahar Rabinoviz
  • 1,939
  • 2
  • 17
  • 28

5 Answers5

5

It needs to be:

void x(void(*function)())
{
  // Whatever...
}

If you're using C++11 you can std::function:

void x(std::function<void()> function)
{
  // Whatever
}
Sean
  • 60,939
  • 11
  • 97
  • 136
  • `std::function` should be reserved for storing type-erased functionoids. For parameter passing, templates are preferred. – Quentin Feb 05 '15 at 16:13
  • @Quentin - do you have a citation for why that's the case? – Sean Feb 05 '15 at 16:24
  • [This Q&A](http://stackoverflow.com/questions/14677997/stdfunction-vs-template) cover it. `std::function` is a type-erased object, and this comes at the price of indirection and dynamic allocation, since nothing is known about the pointee. Passing any functionoid with its type perfectly deduced by a template parameter can be completely inlined and optimized. – Quentin Feb 05 '15 at 16:32
4

Let's take a look at the error message:

invalid conversion from 'void (*)()' to 'void*' [-fpermissive]

It means that void* (a data pointer) is the type specified in x,
but void (*)() (a function pointer) is being passed instead.

So change x to

void x(void (*ptr)())
{
}
Z4-tier
  • 7,287
  • 3
  • 26
  • 42
Axalo
  • 2,953
  • 4
  • 25
  • 39
2

The answer is in the error message. void* is not a pointer to function, void(*)() (for example) is. You should rewrite x as follows :

void x(void (*ptr)()) {

}

A pointer-to-function is written this way :

Ret (*name)(Params)

Where

  • Ret is the pointee's return type
  • name is the name of the pointer
  • Params is the list ofthe pointee's parameters, as you would write them in its declaration.

Example :

double (*ptr)(int, float)

...can point to a function taking an int and a float and returning a double.

Quentin
  • 62,093
  • 7
  • 131
  • 191
1

void* is not a function pointer, it's a void pointer.

To declare a function pointer, use void (*ptr)().

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

We can do some ugly pointer magic, like this:

static void function1( char* c ) {
    printf( "%s", c );
}

void function2( void* ptr ) {
    void(* func)(char*) = (void(*)(char*))ptr;
    func( "a" );
}

int _tmain(int argc, _TCHAR* argv[])
{
    void* f = function1;
    function2( f );
    return 0;
}

This is bad, but it works in such situations.