/* uniduk.c, integrate a Javascript engine in Unicon tectonics: gcc -std=c99 -o uniduk.so -shared -fpic uniduk.c duktape.c -lm */ #include #include "duktape.h" #include "icall.h" /* dukeval, evaluate a Javascript string or from file */ static duk_context *unictx; static int duk_loaded = 0; int dukeval(int argc, descriptor *argv, int fromfile) { /* Need a string argument */ if (argc < 1) Error(103); if (!duk_loaded) { unictx = duk_create_heap_default(); /* if bad init, report program malfunction */ if (!unictx) Error(500); duk_loaded = 1; } /* argument is either a filename or code string */ ArgString(1); if (fromfile) { duk_eval_file(unictx, StringVal(argv[1])); } else { duk_eval_string(unictx, StringVal(argv[1])); } duk_int_t typ = duk_get_type(unictx, -1); switch (typ) { case DUK_TYPE_NONE: case DUK_TYPE_UNDEFINED: RetNull(); break; case DUK_TYPE_NULL: duk_pop(unictx); RetNull(); break; case DUK_TYPE_NUMBER: case DUK_TYPE_BOOLEAN: RetReal(duk_get_number(unictx, -1)); break; case DUK_TYPE_STRING: RetConstString((char *)duk_get_string(unictx, -1)); break; default: fprintf(stderr, "Unsupported Duk type: %d\n", typ); Error(178); break; } return 0; } /* uniduk, a Unicon loadfunc function Usage from Unicon uniduk := loadfunc("./uniduk.so", "uniduk") result := uniduk("print('Hello'); var r = 7 * 6;") */ int uniduk(int argc, descriptor *argv) { int result; result = dukeval(argc, argv, 0); return result; } /* unidukFile, load Duktape code from file Usage from Unicon unidukfile := loadfunc("./uniduk.so", "unidukFile") result := unidukfile("uniduk.js") */ int unidukFile(int argc, descriptor *argv) { int result; result = dukeval(argc, argv, 1); return result; } /* unidukDone, a Unicon loadfunc function for Duktape rundown Usage from Unicon unidukdone := loadfunc("./uniduk.so", "unidukDone") result := unidukDone() Unicon result is &null, by nature of not being set */ int unidukDone(int argc, descriptor *argv) { duk_destroy_heap(unictx); duk_loaded = 0; return 0; }