Assigning a function pointer to a void pointer in C and C ++

I am trying to use the C library from my C ++ project.

The C library has such a function that I have to pass the callback functions to:

void c_function(int args, const void *func){};

So, my C ++ code should call it like this:

int function1(int a) {return a;}
int function2(int a, int b) {return a+b;}

int main(int argc, char *argv[])
{
    c_function(1, function1);
    c_function(2, function2);
    return 0;
}

My problem is that if I compile this C calling code, it works fine and doesn't even have any warnings. However, if I compile the calling code as C ++, it has a compilation error: for example, the conversion from 'int () (int)' to 'const void' is incorrect.

I'm not sure what I need to make it work in C ++. I will have many of these calls in my C ++ program.

My question is: how can I do this work without changing the call code and why does it work in C, but not in C ++? I thought C ++ was a superset of C.

+4

Source: https://habr.com/ru/post/1652659/


All Articles