I have a function which takes a callback as parameter, its signature is:
typedef void(*callback_type)(const* uint32_t data, unint8_t size);
void set_callback(callback_type callback);
The two parameters taken by the callback function are used by a struct so I would like to bind the callback to the struct. C++ has tools to deal with this kind of problems (member functions, lambdas, std::bind, ...). For example, the code I'm trying to achieve in C is equivalent to the C++ code:
set_callback([&](const uint32_t* data, uint8_t size) -> void {
use_data(&the_struct, data, size);
});
The solution I'm looking for has some requirements:
- Language: C (or assembly if anyone is willing to)
- If possible with no imports (these including c standard library)
- Be independent of the compiler (ie. no blocks from GCC or CLang)
Through my researches, I have found the following code, but it does not work in my case and does not really match requirements as it is dependent on non standard features provided by gcc (nested functions and statement expressions):
#define lambda(lambda$_ret, lambda$_args, lambda$_body)\
({\
lambda$_ret lambda$__anon$ lambda$_args\
lambda$_body\
&lambda$__anon$;\
})
Also note that it is possible to modify code in order to take a void pointer (as user data) in a callback which would solve the problem. This is the best solution I have so far and might be the cleanest overall. However, I'd like a solution that does not requires such trick.
Even if you only have a partial solution, I'd be happy to hear about it.
Thanks for taking the time for reading the question and have a good day!
Edit 1: The c++ code involving a lambda does not work (because the lambda captures...). For this to work, std::function or templated arguments must be used. But the point is still clear I think. Thanks to tstanisl for pointing this out.
Edit 2: When I wrote "used by a struct" this effectively makes no sense. What I meant was : a function will use the data provided (data and size parameters) to update members of the structure and do some other computation. I hope this is more clear. Thanks to '4386427' and 'Gaurav Pathak' for their comments.