Menu

#7 Opaque type for custom user structs

open
nobody
5
2013-03-22
2013-03-22
Sanel Zukan
No

This patch will add support for user custom structs with ability to
free them in gc phase.

For example, let we have struct FooStruct we are going to make
visible to scheme and here is how it could be used:

typedef struct FooStruct_t {
  char *str;
  int  num;
} FooStruct;

static void
free_struct(void *o) {
  FooStruct *s = (FooStruct*)o;
  free(s->str);
  free(s);
}

static pointer
new_foo(scheme *sc, pointer args) {
  pointer arg1, arg2;
  FooStruct *s;

  /* parse args to arg1 and arg2, validate and etc. */

  s = malloc(sizeof(FooStruct));
  s->str = strdup(sc->vptr->string_value(arg1));
  s->num = sc->vptr->ivalue(arg2);

  return sc->vptr->mk_opaque(sc, "FOO-STRUCT", tt, free_struct);
}

/* somewhere register 'new_foo' as '(new-foo)' */

after this, by calling (new-foo "test" 33) we will get allocated
structure, where FOO-STRUCT is written in REPL as #<FOO-STRUCT>
when object is printed.

When object is ready for gc-ing, free_func() will be called.

This patch add standard calls like is_opaque(), mk_opaque(),
opaquevalue() and opaquetag(), where opaquetag() will return assigned
tag and opaquevalue() set user value.

As rest of tinyscheme code, if unset USE_OPAQUE_TYPE macro, opaque
types will not be compiled.

1 Attachments

Discussion


Log in to post a comment.