[previous] [up] [next]     [contents] [index]
Next: MzScheme Architecture Up: Inside PLT MzScheme Previous: This Manual

Overview

Writing MzScheme Extensions

To write a C/C++-based extension to MzScheme, follow these steps:

See also the general integration notes at the end of this section.

As an example, the following C code defines an extension that returns "hello world" when it is loaded:

 #include "escheme.h"
 Scheme_Object *scheme_initialize(Scheme_Env *env) {
   return scheme_make_string("hello world");
 }
 Scheme_Object *scheme_reload(Scheme_Env *env) {
   return scheme_initialize(env); /* Nothing special for reload */
 }

Assuming that this code is in the file hw.c, the extension is compiled under Unix with the following two commands:

  mzc --cc hw.c
  mzc --ld hw.so hw.o

Embedding MzScheme into a Program

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

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;
}

General Integration Notes

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 extension, static variables that contain pointers to collectable memory must be registered using scheme_register_global (but registered variables need not necessarily contain a collectable pointer at all times). When MzScheme is embedded in an application, all globals are automaticaly registered.


[previous] [up] [next]     [contents] [index]
Next: MzScheme Architecture Up: Inside PLT MzScheme Previous: This Manual

PLT