[Ecls-list] Example.c

Michael O'Connor moconnor59 at yahoo.com
Mon Mar 8 08:05:05 UTC 2004


I thought I'd send an example program I've written to
this list, mainly because I couldn't find such an
example when I was looking around.

It's meant to show how to embed the interpreter in a
C/C++ application, and pass values between it and the
C/C++ layer. This stuff will be obvious to regular ECL
users, but I would have found it very useful when
first looking at ECL (particularly as I come from a
C/C++, rather than Lisp, background).

Michael


example.c:

#include <ecl.h>
#include <stdio.h>
#include <stdlib.h>

static int a = 0;
static int b = 0;
static int c = 0;

static cl_object _get_a()
{
    return MAKE_FIXNUM(a);
}

static cl_object _get_b()
{
    return MAKE_FIXNUM(b);
}

static cl_object _set_c(cl_object lispnum)
{
    c = fixint(lispnum);
    return Cnil;
}


int main(int argc, char **argv)
{
    if (argc < 3) {
        printf("Usage:\t%s <a> <b>\n",
basename(argv[0]));
        return 0;
    }
    a = atoi(argv[1]);
    b = atoi(argv[2]);

    /* Initialise Lisp interpreter */
    char *interpreter = "ECL";
    cl_boot(1, &interpreter);

	/* Register callback functions */
    typedef cl_object (*CL_CALLBACK)();
    cl_def_c_function(cl_intern(1,
make_simple_string("%GET-A")), _get_a, 0);
    cl_def_c_function(cl_intern(1,
make_simple_string("%GET-B")), _get_b, 0);
    cl_def_c_function(cl_intern(1,
make_simple_string("%SET-C")), (CL_CALLBACK)_set_c,
1);

	/* I could call the following in place of the
remainder of this code,
	   but I want to read / run the Lisp code as separate
steps
    cl_load(3, make_simple_string("example.lisp"),
make_keyword("VERBOSE"), Cnil);
    */

	/* Read Lisp code */
    cl_object file_handle = cl_open(1,
make_simple_string("example.lisp"));
    cl_object bytecode = cl_read(1, file_handle);
    cl_close(1, file_handle);

	/* Run Lisp code, and check result */
    cl_object result = si_safe_eval(1, bytecode);
    if (type_of(result) == t_symbol
    &&  equal(cl_symbol_name(result),
make_simple_string("ERROR")))
    {
        printf("Error!\n");
    }
    else
    {
        printf("Result = %d\n", c);
    }

    return 0;
}


example.lisp:

(%set-c (+ (%get-a) (%get-b)))


__________________________________
Do you Yahoo!?
Yahoo! Search - Find what you’re looking for faster
http://search.yahoo.com




More information about the ecl-devel mailing list