1

I have a function that takes following argument:

int setvalue(void (*)(void *));

In order to satisfy parameter: void (*)(void *), I created a function like this:

    static void *freeFunction(void *freeAbc)
    {
        AllocAbc *abc = (AllocAbc*) freeAbc; 
        if (abc)
        {
            delete abc;
        }
        return NULL;
    }

And I'm trying to use both together as :

    AllocAbc *allocAbc = new AllocAbc();
    ...
    void *freeAbc = (void *) allocAbc;
    if (setvalue (freeFunction(freeAbc)) < 0)
    {           
        ...
    }

I get an error saying error: invalid conversion from ‘void*’ to ‘void (*)(void*)’ [-fpermissive]

What should be changed here (either in freeFunction definition or the way I use both) to make it work.

Thanks.

sth
  • 222,467
  • 53
  • 283
  • 367
Singo
  • 83
  • 2
  • 6

3 Answers3

3

Your function should return void not void *.

static void freeFunction(void *freeAbc)
{
    ...
}

The (*) indicates that setvalue's parameter is a function pointer. It's not part of that function's return type.

(void (*)(void *)
 ^^^^  ^  ^^^^^^
  ||   |    ||
  ||   |    ++ parameter types
  ||   |
  ||   + function pointer
  ||
  ++ return type 

Also, to call setvalue you need to pass the function name without calling it.

if (setvalue(freeFunction) < 0)

To make it clearer, you may want to add an & to indicate that you're not calling the function. & is optional when passing function pointers, so this is just a readability thing.

if (setvalue(&freeFunction) < 0)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks John for detailed explanation. The code does compile now. But 1 more question. I am actually using freeFunction to free the memory passed in by the *freeAbc. How will the function receive the memory address when we are just specifying if (setvalue(&freeFunction) < 0)? – Singo May 05 '15 at 22:44
  • `setvalue` will have to pass that value when it calls the function. Perhaps you could add a second parameter to `setvalue` so it accepts both a function pointer and a `void *` data argument, and then it calls the function with that data pointer. – John Kugelman May 05 '15 at 22:53
3

You have two problems:

  1. Your freeFunction returns void instead of void *.
  2. You are passing the return value of freeFunction(freeAbc) into setValue instead of a pointer to the function itself.
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
1

freeFunction returns void*, but setvalue wants a function that returns void. They are clearly not the same type.

Also you're passing the return value of freeFunction to setvalue, but setvalue expects a function pointer.

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