I have a situation in C as well as in C++ which can be best solved with something like the Python like decorators: I have few a functions which I'd like to wrap around with something else so that before the function enters some statements are performs and when it leaves some other functionality is executed.
For instance, I have a few functions in a library C file which when called should lock a semaphore and before returning the control to callee, should release the semaphore. without the lock they have following structure:
int f1(int)
{
...
...
}
int f2(char*)
{
....
}
int f3(blabla)
{
....
}
... fn(...)
I'd like to define a global semaphore which should be locked before each of these functions is called and released when the function is returned. I'd like to do it with as much simplicity as possible; something close to this:
#lockprotected
int f1(int)
{
... /* nothing changed over here */
}
#endlockprotected
or something like
int f1(int)
{
... /* nothing changed over here */
}
#lockprotected f1
What I don't want is:
- Change the function names as they are library functions and are being called from many places.
- Explicitly place any statement before return calls as most of the functions have many early returns in between. Or for that matter change any internals of the function.
What would be the most elegant way?