[previous] [up] [next]     [index]
Next: MzScheme and Threads Up: Overview Previous: Writing MzScheme Extensions

Embedding MzScheme into a Program

To embed MzScheme in a program, first download the MzScheme source code. Then, follow these steps:

Scheme values are garbage collected using a conservative garbage collector, so pointers to MzScheme objects can be kept in registers, stack variables, or structures allocated with scheme_malloc. In an embedding application, static variables are also automatically registered as roots for garbage collection (but see the Windows-specific note below).

For example, the following is a simple embedding program which evaluates all expressions provided on the command line and displays the results:

#include "scheme.h"
int main(int argc, char *argv[])
{
  Scheme_Env *e = scheme_basic_env();
  Scheme_Object *curout = scheme_get_param(scheme_config, MZCONFIG_OUTPUT_PORT);
  int i;
  for (i = 1; i < argc; i++) {
    if (scheme_setjmp(scheme_error_buf)) {
      return -1; /* There was an error */
    } else {
      Scheme_Object *v = scheme_eval_string(argv[i], e);
      scheme_display(v, curout);
      scheme_display(scheme_make_character('\n'), curout);
    }
  }
  return 0;
}

Under Windows, the garbage collector finds static variables in an embeddeding program by examining all memory pages. This strategy fails if a program contains multiple Windows threads; a page may get unmapped by a thread while the collector is examining the page, causing the collector to crash. To avoid this problem, set GC_use_registered_statics to 1 before calling any scheme_ function, and register all globals with GC_use_registered_statics to 1 before calling any GC or MzScheme function, and register all globals with scheme_register_static.


[previous] [up] [next]     [index]
Next: MzScheme and Threads Up: Overview Previous: Writing MzScheme Extensions

PLT