## 9.9 Example of Using the Foreign Interface

Below is an example showing all stages of the declaration of a foreign predicate that transforms atoms possibly holding uppercase letters into an atom only holding lower case letters. Figure 12 shows the C-source file, figure 13 illustrates compiling and loading of foreign code.

    /*  Include file depends on local installation */
    #include <SWI-Prolog.h>
    #include <stdlib.h>
    #include <ctype.h>

    foreign_t
    pl_lowercase(term_t u, term_t l)
    { char *copy;
      char *s, *q;
      int rval;

      if ( !PL_get_atom_chars(u, &s) )
        return PL_warning("lowercase/2: instantiation fault");
      copy = malloc(strlen(s)+1);

      for( q=copy; *s; q++, s++)
        *q = (isupper(*s) ? tolower(*s) : *s);
      *q = '\0';

      rval = PL_unify_atom_chars(l, copy);
      free(copy);

      return rval;
    }

    install_t
    install()
    { PL_register_foreign("lowercase", 2, pl_lowercase, 0);
    }

Figure 12 : Lowercase source file

    % gcc -I/usr/local/lib/pl-\plversion/include -fpic -c lowercase.c
    % gcc -shared -o lowercase.so lowercase.o
    % pl
    Welcome to SWI-Prolog (Version \plversion)
    Copyright (c) 1993-1996 University of Amsterdam.  All rights reserved.

    For help, use ?- help(Topic). or ?- apropos(Word).

    1 ?- load_foreign_library(lowercase).

    Yes
    2 ?- lowercase('Hello World!', L).

    L = 'hello world!'

    Yes

Figure 13 : Compiling the C-source and loading the object file