I have an API for managing a camera configuration. There are 344 individual options to manage. When a certain value changes the API calls a callback function to notify the program. The register function takes a
void RegisterCallback(Option * ptr, void (fn*)(void*))
function pointer as a callback function. I cannot use a single function for callback, because I do now where is the callback coming from.
One solution is to create 344 individual callback functions:
void callback0(void*);
void callback1(void*);
...
void callback{n-1}(void*);
static void(*)(void*) callbacks[] = {callback0, callback1, ..., callback{n-1}};
For this solution I would need to generate the header with a separate tool/script.
Another solution would be to use some preprocessor magic (BoostPP), like
BOOST_PP_FOR((0,1024), PRED, OP, MYSTERIOUS_CALLBACK_MACRO);
In my experience these macros are unreadable for the developers, and are difficult to maintain.
Ideally I could use something like
RegisterCallback(popt, [n](void*){/*n-th callback*/});
But the lambda function is a functor and not a function pointer.
My question is this: Can I create these functions dynamically? Or is there a better solution for this problem than the two above?
Thank You.
EDIT
I have gotten an answer from Botje. Passing an object to a function callback requires You to access the code on the binary level (beyond that of C/C++). If You can permit that, then libffi can be a solution, as it generates a specific pointer to each instance of Your function. It is widely supported, but, for example Visual Studio Compiler is not on the list.
EDIT 2 As others pointed it out it should work with VS too.