Skip to content

Instantly share code, notes, and snippets.

@chrisbarrett
Last active March 24, 2017 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbarrett/5794681 to your computer and use it in GitHub Desktop.
Save chrisbarrett/5794681 to your computer and use it in GitHub Desktop.
C object using blocks language extension
#include <assert.h>
#include <stdlib.h>
#define Array_new(name, type, len) \
typedef void(^name##_each)(type); \
typedef void(^name##_each_i)(type, int); \
\
struct { \
type *data; \
size_t length; \
void(^free)(); \
type(^get)(int); \
void(^set)(int, type); \
void(^each)(name##_each); \
void(^each_i)(name##_each_i); \
} name; \
\
name.data = malloc(len * sizeof(type)); \
name.length = len; \
\
name.free = ^{ free(name.data); }; \
\
name.get = ^(int i){ \
assert(i<= name.length); \
return ((type *)name.data)[i]; \
}; \
\
name.set = ^(int i, type value){ \
assert(i<= name.length); \
((type*)name.data)[i] = value; \
}; \
\
name.each = ^(name##_each action){ \
for (int i=0; i<name.length; ++i) \
action(name.get(i)); \
}; \
\
name.each_i = ^(name##_each_i action){ \
for (int i=0; i<name.length; ++i) \
action(name.get(i), i); \
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment