delegate.c

Abstract Function Pointers in C
Download

delegate.c Ranking & Summary

Advertisement

  • Rating:
  • License:
  • Other/Proprietary Li...
  • Price:
  • FREE
  • Publisher Name:
  • William Ahern
  • Publisher web site:
  • http://25thandclement.com/~william/projects/

delegate.c Tags


delegate.c Description

Abstract Function Pointers in C C libraries and application components often make use of function callbacks to interface with other code. Sometimes the required signature of the function callback is annoying and/or introduces obscurity and indirection which, hitherto, one had to silently suffer.The delegate.c package implements a sort of abstract function pointer by capturing a function signature (delegate()) and exposing it through a simple interface (invoke()). It provides something loosely approximating lambda expressions; or even more analogous, C# delegates.The implementation depends on GCC's type introspection builtins, and on libffi. Both are widely portable.All the magic in the delegate() macro should be constant folded by GCC, even at optimization level 0. The generated code should not be any slower than using libffi directly (however one might do so).The original purpose of this code was to abstract the libevent API. The core implementation is entirely generic. This generic implementation is then used to provide an event_set() / event_add() wrapper: event_delegate().Passing a typical void (*)(int, short, void *) callback is statically detected by event_delegate(). In such a case, only the third argument is necessary; the first two are implicit. libffi is entirely bypassed in this case, introducing no run-time penalty. This is useful for micro-optimizing those few callbacks which get all the traffic.Usage:/* Simple example of delegate() and invoke(). */struct delegate del = DELEGATE_INITIALIZER;delegate(&del, &my_func, arg0, arg1, ...);invoke(&del);/* Execute exit(EXIT_SUCCESS) on SIGTERM or after 60 seconds. */struct event_delegate event = EVENT_DELEGATE_INITIALIZER;int sig = SIGTERM;short events = EV_SIGNAL|EV_PERSIST;struct timeval timeout = { 60, 0 };event_delegate(&event, sig, events, &timeout, &exit, EXIT_SUCCESS);event_dispatch();A small regression utility can be built from the source. Defining DELEGATE_MAIN will expose the main() definition. What's New in This Release: · Fix bug that would continually re-add the event even if already pending.


delegate.c Related Software