Posted to tcl by gps at Mon Apr 06 10:44:54 GMT 2009view raw
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- enum {
- FORTCL_CELL_TYPE_INT = 1,
- FORTCL_CELL_TYPE_LONG,
- FORTCL_CELL_TYPE_STRING,
- FORTCL_CELL_TYPE_BIGNUM
- };
- struct fortcl_cell {
- union {
- int i;
- long l;
- size_t string_offset;
- size_t bignum_offset;
- } types;
- char type;
- };
- struct fortcl_interp {
- char **strings;
- size_t strings_used;
- };
- struct fortcl_interp *
- fortcl_interp_create(void) {
- struct fortcl_interp *interp;
- interp = malloc(sizeof *interp);
- if(NULL == interp) {
- perror("malloc");
- return NULL;
- }
- return interp;
- }
- struct fortcl_cell
- fortcl_string_create(struct fortcl_interp *interp, const char *cp, size_t length) {
- struct fortcl_cell result;
- /*
- * This is just an example. The real version would expand the strings array
- * if needed, and try to enlarge it by N, where N > 1 to avoid reallocs.
- */
- interp->strings = malloc(sizeof(*(interp->strings)));
- /*error checking not added*/
- result.types.string_offset = interp->strings_used;
- result.type = FORTCL_CELL_TYPE_STRING;
- interp->strings[interp->strings_used] = strdup(cp);
- /*error checking for strdup not added.*/
- interp->strings_used += 1;
- return result;
- }
- char *
- fortcl_string_get(struct fortcl_interp *interp, struct fortcl_cell str) {
- if(FORTCL_CELL_TYPE_STRING == str.type) {
- return interp->strings[str.types.string_offset];
- } else {
- /* perhaps fortcl_string_create... and return the pointer. */
- return NULL;
- }
- }
- void
- fortcl_example_puts(struct fortcl_interp *interp, struct fortcl_cell str) {
- puts(fortcl_string_get(interp, str));
- }
- struct fortcl_cell
- fortcl_integer_create(int i) {
- struct fortcl_cell cell;
- cell.types.i = i;
- cell.type = FORTCL_CELL_TYPE_INT;
- return cell;
- }
- struct fortcl_cell
- fortcl_example_multiply(struct fortcl_interp *interp, size_t objc, struct fortcl_cell *argv) {
- struct fortcl_cell result;
- result.types.i = argv[0].types.i * argv[1].types.i;
- result.type = FORTCL_CELL_TYPE_INT;
- return result;
- }
- int
- main(int argc, char *argv[]) {
- struct fortcl_interp *interp;
- struct fortcl_cell num[2];
- struct fortcl_cell str;
- struct fortcl_cell magic;
- interp = fortcl_interp_create();
- if(NULL == interp) {
- return EXIT_FAILURE;
- }
- str = fortcl_string_create(interp, "Hello", 5);
- fortcl_example_puts(interp, str);
- num[0] = fortcl_integer_create(6);
- num[1] = fortcl_integer_create(7);
- magic = fortcl_example_multiply(interp, 2, num);
- printf("The magic number is: %d\n", magic.types.i);
- return EXIT_SUCCESS;
- }