Today I want to show you some of the plain old C black magic. This is the magic of direct user context manipulating. You can use this low-level feature to implement some high-level language abstractions such as generators and ruby-like blocks. Let's start with an example(test1.c):
The code above is a valid C code. It produces such output:
Let's take a look on the implementation of used generators (enumerate, for_each in gens.c):
As you can see, the implementation of generators is pretty straightforward. All the magic is done in cblocks.h:
Manual pages for swapcontext and getcontext can help in understanding what's going on here.
- It's possible to implement nifty language features in C using its low-level features. The generators described above can be even used to build cooperative multitasking systems.
- It doesn't mean that you should do it just because you can ;). Beware that context manipulating doesn't work on all platforms.
- You can find the source code on github. The code should be considered just a playground so please forgive me its untidiness. If you want something mature(e.g., you're seeking for coroutines support in C), check out the libtask, libtorque or libcoro
As always I will be happy to accept any criticism on the code above. Feel free to contact me in any way you can imagine.