Blocks (C language extension)

Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+,{{cite web|url=https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html|title=Blocks Programming Topics|website=Apple Developer|publisher=Apple Inc.|accessdate=2011-03-08}} although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+{{Cite web|url=https://code.google.com/p/plblocks/|title = Google Code Archive - Long-term storage for Google Code Project Hosting}} and non-Apple systems.

Apple designed blocks with the explicit goal of making it easier to write programs for the Grand Central Dispatch threading architecture,{{cite web|url=https://images.apple.com/macosx/technology/docs/GrandCentral_TB_brief_20090903.pdf|publisher=Apple|type=technology brief|title=Grand Central Dispatch|archive-url=https://web.archive.org/web/20090920043909/http://images.apple.com/macosx/technology/docs/GrandCentral_TB_brief_20090903.pdf|date=2009-09-03|archive-date=2009-09-20|access-date=June 9, 2009}}{{cite web|url=https://arstechnica.com/apple/reviews/2009/08/mac-os-x-10-6.ars/10|title=Mac OS X 10.6 Snow Leopard: the Ars Technica review: Blocks|first=John|last=Siracusa|date=September 1, 2009|work=Ars Technica}} although it is independent of that architecture and can be used in much the same way as closures in other languages. Apple has implemented blocks both in their own branch of the GNU Compiler Collection and in the upstream Clang LLVM compiler front end. Language runtime library support for blocks is also available as part of the LLVM project. The Khronos group uses blocks syntax to enqueue kernels from within kernels as of version 2.0 of OpenCL.{{cite web|url=http://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#page=173|title=The OpenCL C Specification. Version 2.0. Document Revision 11|publisher=Khronos OpenCL Working Group|editor-first=Aaftab|editor-last=Munshi|date=2013-07-13|archive-url=https://web.archive.org/web/20131105084709/http://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#page=173|page=173|archive-date=2013-11-05|access-date=2013-07-23}}

Like function definitions, blocks can take arguments, and declare their own variables internally. Unlike ordinary C function definitions, their value can capture state from their surrounding context. A block definition produces an opaque value which contains both a reference to the code within the block and a snapshot of the current state of local stack variables at the time of its definition. The block may be later invoked in the same manner as a function pointer. The block may be assigned to variables, passed to functions, and otherwise treated like a normal function pointer, although the application programmer (or the API) must mark the block with a special operator (Block_copy) if it's to be used outside the scope in which it was defined.

Given a block value, the code within the block can be executed at any later time by calling it, using the same syntax that would be used for calling a function.

<span lang="English">Examples</span>

A simple example capturing mutable state in the surrounding scope is an integer range iterator:{{Cite web

| last1 = Bengtsson

| first1 = Joachim

| title = Programming with C Blocks on Apple Devices

| url = http://thirdcog.eu/pwcblocks/

| archive-url = https://web.archive.org/web/20171115165448/http://thirdcog.eu/pwcblocks

| archive-date = 2017-11-15

| access-date = 2009-09-17

| url-status = dead

}}

/* blocks-test.c */

  1. include
  2. include

/* Type of block taking nothing returning an int */

typedef int (^IntBlock)();

IntBlock MakeCounter(int start, int increment) {

__block int i = start;

return Block_copy( ^(void) {

int ret = i;

i += increment;

return ret;

});

}

int main(void) {

IntBlock mycounter = MakeCounter(5, 2);

printf("First call: %d\n", mycounter());

printf("Second call: %d\n", mycounter());

printf("Third call: %d\n", mycounter());

/* because it was copied, it must also be released */

Block_release(mycounter);

return 0;

}

= Compile and execute =

$ clang -fblocks blocks-test.c # Mac OS X

$ ./a.out

First call: 5

Second call: 7

Third call: 9

The blocks runtime is not part of the C library(s) linked by default on some systems. If this is the case, it is required to explicitly link to this library:

$ clang -fblocks blocks-test.c -lBlocksRuntime # Linux

The runtime is a part of clang's runtime, but is sometimes not installed with the clang package. A standalone runtime extracted from compiler-rt is available.{{cite web |title=mackyle/blocksruntime: standalone blocks runtime |url=http://mackyle.github.io/blocksruntime/ |accessdate=15 January 2020}}

Relation to GCC nested functions

Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions.{{cite web|url=https://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Nested-Functions.html#Nested-Functions|title=Nested Functions: Using the GNU Compiler Collection (GCC)}} However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.

GCC-style nested functions currently use dynamic creation of executable thunks on most architectures when taking the address of the nested function. On most architectures (including X86), these thunks are created on the stack, which requires marking the stack executable. Executable stacks are generally considered to be a potential security hole. Blocks do not require the use of executable thunks, so they do not share this weakness. On the other hand, blocks introduces a completely new type for the pointer, while pointers to nested functions in GCC are regular function pointers and can be used directly with existing code.

See also

References

{{reflist}}