5

I'm trying to use a C library from my C++ project.

The C library has a function like this that I'm supposed to pass callback functions into:

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 issue is that if I compile this calling code as C, it works fine and doesn't even have any warnings. If I compile the calling code as C++, however, it has the compile error: invalid conversion from 'int ()(int)' to 'const void', for example.

I'm not sure what I need to do to get it working in C++. I'm going to have a lot of these calls in my C++ program.

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

JakeL
  • 69
  • 2
  • Why am I getting downvoted? I tried to put a lot of effort into simplifying my code and explaining my question clearly. – JakeL Aug 26 '16 at 23:33
  • Visual Studio 2005 and 2010 don't report errors. I though void * was compatible with just about any pointer. – rcgldr Aug 26 '16 at 23:54
  • But this is actually a well written question. Simplified to the max, and yet very understandable. +1 – Mirakurun Aug 26 '16 at 23:55
  • @rcgldr Of course it isn't. Function and object pointers are separated. – 2501 Aug 26 '16 at 23:56
  • @JakeL I don't know how you're compiling your code, since you didn't show it, but, casting between function and object pointers is not defined in C as it isn't in C++. – 2501 Aug 26 '16 at 23:58
  • @JakeL - Perhaps changing the prototype to something like extern "C" c_function(int, int( * )(...)); or extern "C" c_function(int, int( * )(int, ...)); might work, where the (...) is used to deal with variable number of arguments. – rcgldr Aug 27 '16 at 00:48

0 Answers0