I'm writing a C library which I would like to be usable from both C and C++. At one moment, it should take a callback from the user with 0-3 arguments, which will be called at some pointer later. Like this (a copy of the code is available as GitHub Gist too):
// app_c.c
#include <stdio.h>
#include "lib.h"
double f0(void) {
return 123;
}
double f2(double a, double b) {
return a + b;
}
int main() {
cb_arity = 0;
cb_func = f0;
printf("%f\n", cb_call());
cb_arity = 2;
cb_func = f2;
printf("%f\n", cb_call());
}
I was able to create a pointer to a C function which takes unknown (but still fixed) number of arguments, note it's void (*cb_func)(), not void (*cb_func)(void):
// lib.h
#ifndef LIB_H_
#define LIB_H_
#ifdef __cplusplus
extern "C" {
#endif
extern int cb_arity;
extern double (*cb_func)();
double cb_call(void);
#ifdef __cplusplus
}
#endif
#endif // LIB_H_
// lib.c
#include "lib.h"
#include <stdlib.h>
int cb_arity;
double (*cb_func)();
double cb_call(void) {
switch (cb_arity) {
case 0:
return cb_func();
case 1:
return cb_func(10.0);
case 2:
return cb_func(10.0, 20.0);
case 3:
return cb_func(10.0, 20.0, 30.0);
default:
abort();
}
}
It compiles and runs successfully both on my machine and Wandbox. As far as I understand, no UB is invoked.
Now I would like to make it work in C++ as well. Unfortunately, it looks like I now need reinterpret_cast because () means "no arguments" in C++, not "unknown number of arguments":
// app_cpp.cpp
#include <stdio.h>
#include "lib.h"
int main() {
cb_arity = 0;
cb_func = []() { return 123.0; };
printf("%f\n", cb_call());
cb_arity = 2;
cb_func = reinterpret_cast<double(*)()>(static_cast<double(*)(double, double)>(
[](double a, double b) { return a + b; }
));
printf("%f\n", cb_call());
}
As far as I understand, no UB is invoked here as well: although I convert function pointer double(*)(double, double) to double(*)(void) in C++, it's converted back to double(*)(double, double) in C code right before calling.
Is there any way to get rid of these ugly casts in C++ code? I've tried specifying type of cb_func as void(*)(...), but C++ still won't implicitly convert double(*)(double, double) to it.