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!
A Working Definition of a Closure with a JavaScript Example
A closure is a kind of object that contains a pointer or reference of some kind to a function to be executed along with the an instance of the data needed by the function.
An example in JavaScript from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures is
which could then be used like:
Some of the Obstacles to Overcome with C
The C programming language is a statically typed language, unlike JavaScript, nor does it have garbage collection, and some other features that make it easy to do closures in JavaScript or other languages with intrinsic support for closures.
One large obstacle for closures in Standard C is the lack of language support for the kind of construct in the JavaScript example in which the closure includes not only the function but also a copy of data that is captured when the closure is created, a way of saving state which can then be used when the closure is executed along with any additional arguments provided at the time the closure function is invoked.
However C does have some basic building blocks which can provide the tools for creating a kind of closure. Some of the difficulties are (1) memory management is the duty of the programmer, no garbage collection, (2) functions and data are separated, no classes or class type mechanics, (3) statically typed so no run time discovery of data types or data sizes, and (4) poor language facilities for capturing state data at the time the closure is created.
One thing that makes something of a closure facility possible with C is the
void *
pointer and usingunsigned char
as a kind of general purpose memory type which is then transformed into other types through casting.An Implementation With Standard C and a Bit of Stretching Here and There
NOTE: The following example depends on a stack based argument passing convention as is used with most x86 32 bit compilers. Most compilers also allow for a calling convention to be specified other than stack based argument passing such as the
__fastcall
modifier of Visual Studio. The default for x64 and 64 bit Visual Studio is to use the__fastcall
convention by default so that function arguments are passed in registers and not on the stack. See Overview of x64 Calling Conventions in the Microsoft MSDN as well as How to set function arguments in assembly during runtime in a 64bit application on Windows? as well as the various answers and comments in How are variable arguments implemented in gcc? .One thing that we can do is to solve this problem of providing some kind of closure facility for C is to simplify the problem. Better to provide an 80% solution that is useful for a majority of applications than no solution at all.
One such simplification is to only support functions that do not return a value, in other words functions declared as
void func_name()
. We are also going to give up compile time type checking of the function argument list since this approach builds the function argument list at run time. Neither one of these things that we are giving up are trivial so the question is whether the value of this approach to closures in C outweighs what we are giving up.First of all lets define our closure data area. The closure data area represents the memory area we are going to use to contain the information we need for a closure. The minimum amount of data I can think of is a pointer to the function to execute and a copy of the data to be provided to the function as arguments.
In this case we are going to provide any captured state data needed by the function as an argument to the function.
We also want to have some basic safe guards in place so that we will fail reasonably safely. Unfortunately the safety rails are a bit weak with some of the work arounds we are using to implement a form of closures.
The Source Code
The following source code was developed using Visual Studio 2017 Community Edition in a .c C source file.
The data area is a struct that contains some management data, a pointer to the function, and an open ended data area.
Next we create a function that will initialize a closure data area.
This function is designed to accept a pointer to a data area which gives flexibility as to how the user of the function wants to manage memory. They can either use some memory on the stack or static memory or they can use heap memory via the
malloc()
function.or
Next we provide a function that allows us to add data and arguments to our closure. The purpose of this function is to build up the closure data so that when closure function is invoked, the closure function will be provided any data it needs to do its job.
And to make this a bit simpler to use lets provide a wrapping macro which is generally handy but does have limitations since it is C Processor text manipulation.
so we could then use something like the following source code:
Invoking the Closure: The execClosure() Function
The last piece to this is the
execClosure()
function to execute the closure function with its data. What we are doing in this function is to copy the argument list supplied in the closure data structure onto the stack as we invoke the function.What we do is cast the args area of the closure data to a pointer to a struct containing an
unsigned char
array and then dereference the pointer so that the C compiler will put a copy of the arguments onto the stack before it calls the function in the closure.To make it easier to create the
execClosure()
function, we will create a macro that makes it easy to create the various sizes of structs we need.Then we use this macro to create a series of tests to determine how to call the closure function. The sizes chosen here may need tweaking for particular applications. These sizes are arbitrary and since the closure data will rarely be of the same size, this is not efficiently using stack space. And there is the possibility that there may be more closure data than we have allowed for.
We return the pointer to the closure in order to make it easily available.
An Example Using the Library Developed
We can use the above as follows. First a couple of example functions that don't really do much.
Next we build our closures and execute them.
Which gives an output of
Well What About Currying?
Next we could make a modification to our closure struct to allow us to do currying of functions.
with the supporting functions for currying and resetting of a curry point being
The source code for testing this could be:
with the output of
The ANSI C has not a support for closure, as well as nested functions. Workaround for it is usage simple "struct".
Simple example closure for sum two numbers.
Usage:
Result:
On C++11 it will be achived by use lambda expression.
A result, after compilation with a flag -std=c++11.
GCC and clang have the blocks extension, which is essentially closures in C.
On this page you can find a description on how to do closures in C:
http://brodowsky.it-sky.net/2014/06/20/closures-in-c-and-scala/
The idea is that a struct is needed and that struct contains the function pointer, but gets provided to the function as first argument. Apart from the fact that it requires a lot of boiler plate code and the memory management is off course an issue, this works and provides the power and possibilities of other languages' closures.
Using FFCALL,
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.
GCC supports inner functions, but not closures. C++0x will have closures. No version of C that I'm aware of, and certainly no standard version, provides that level of awesome.
Phoenix, which is part of Boost, provides closures in C++.