Search code examples
cclosures

Is there a a way to achieve closures in C


I would like this to work, but it does not:

#include <stdio.h>

typedef struct closure_s {
  void (*incrementer) ();
  void (*emitter) ();
} closure;

closure emit(int in) {

  void incrementer() {
    in++;
  }

  void emitter() {
    printf("%d\n", in);
  }

  return (closure) {
    incrementer,
    emitter
  };
}

main() {
  closure test[] = {
    emit(10),
    emit(20)
  };

  test[0] . incrementer();
  test[1] . incrementer();

  test[0] . emitter();
  test[1] . emitter();
}

It actually does compile and does work for 1 instance ... but the second one fails. Any idea how to get closures in C?

It would be truly awesome!


Solution

  • Using FFCALL,

    #include <callback.h>
    #include <stdio.h>
    static void incrementer_(int *in) {
        ++*in;
    }
    static void emitter_(int *in) {
        printf("%d\n", *in);
    }
    int main() {
        int in1 = 10, in2 = 20;
        int (*incrementer1)() = alloc_callback(&incrementer_, &in1);
        int (*emitter1)() = alloc_callback(&emitter_, &in1);
        int (*incrementer2)() = alloc_callback(&incrementer_, &in2);
        int (*emitter2)() = alloc_callback(&emitter_, &in2);
        incrementer1();
        incrementer2();
        emitter1();
        emitter2();
        free_callback(incrementer1);
        free_callback(incrementer2);
        free_callback(emitter1);
        free_callback(emitter2);
    }
    

    But usually in C you end up passing extra arguments around to fake closures.


    Apple has a non-standard extension to C called blocks, which do work much like closures.