How to pass a C++ function into a C one that takes function pointer with unspecified parameter?

125 Views Asked by At

My C dependency library (edit: actually we're writing a Postgres extension so the dependency is Postgres 14.4) has a function

bool expression_tree_walker(Node *node, bool (*walker) (), void *context)

in which the second parameter bool (*walker) () takes unspecified number of parameters according to https://en.cppreference.com/w/c/language/function_declaration#:~:text=unspecified.

In my C++ code, I want to pass the function static bool my_walker(Node *node, struct my_ctx *ctx) into expression_tree_walker, but since C++ interprets bool (*walker) () as a function that takes no parameter, passing it directly won't compile:

enter image description here

I know I can cast it into bool (*) () but that won't pass the -Wcast-function-type check that we are using. I also know I can use double-casting like (bool (*) ()) (void (*) ()) my_walker to suppress this warning but I think it's a bit hacky. Are there any recommended, better way to make this happen?

1

There are 1 best solutions below

0
Davis Herring On

There can’t be a very clean way of handling this, since the C declaration is simply wrong when interpreted as C++. That said, the C type bool() is closest to the C/C++ type bool(...) and should be ABI compatible with it (as they both apply the default argument promotions).

The first step is thus to define your function to be variadic (even if all it does is invoke va_arg a couple of times and then call the real implementation). Afterwards you can, with similar degrees of violence against the language, either add the ellipsis to the declaration of the callback parameter or cast the pointer to your function. Any resulting warning is yours to keep.