Node:Type checking, Next:, Previous:Creating Instances, Up:Defining New Types (Smobs)



18.3.3 Type checking

Functions that operate on smobs should aggressively check the types of their arguments, to avoid misinterpreting some other datatype as a smob, and perhaps causing a segmentation fault. Fortunately, this is pretty simple to do. The function need only verify that its argument is a non-immediate, whose first word is the type tag returned by scm_make_smob_type.

For example, here is a simple function that operates on an image smob, and checks the type of its argument. We also present an expanded version of the init_image_type function, to make clear_image and the image constructor function make_image visible to Scheme code.

SCM
clear_image (SCM image_smob)
{
  int area;
  struct image *image;

  SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
              image_smob, SCM_ARG1, "clear-image");

  image = (struct image *) SCM_SMOB_DATA (image_smob);
  area = image->width * image->height;
  memset (image->pixels, 0, area);

  /* Invoke the image's update function.  */
  if (image->update_func != SCM_BOOL_F)
    scm_apply (image->update_func, SCM_EOL, SCM_EOL);

  return SCM_UNSPECIFIED;
}


void
init_image_type (void)
{
  image_tag = scm_make_smob_type ("image", sizeof (struct image));
  scm_set_smob_mark (image_tag, mark_image);
  scm_set_smob_free (image_tag, free_image);
  scm_set_smob_print (image_tag, print_image);

  scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image);
  scm_c_define_gsubr ("make-image", 3, 0, 0, make_image);
}