/* Jems Scripting Language Demo */ #include <iostream> #include "jvm.hpp" using namespace std; #define INVALID_INDEX -1 // host API functions jvm_var HAPI_Print(jvm_var *params) { // first parameter is the string which should be printed string str = params[0]; // jvm_var is automatically cast to string cout << str; // no return value needed (but return is mandatory) return jvm_var(); } jvm_var HAPI_Gets(jvm_var *params) { string str; cin >> str; // the string submitted by the user is returned return str; // jvm_var is automatically constructed from string } int main() { virtualmachine jvm; // virtual machine instance int script; // script index script = jvm.add_script_file("demo.jse"); // load script executable if (script == INVALID_INDEX) { cerr << "An error occurred while loading demo.jse!" << endl; return -1; } // registration of host API functions jvm.register_host("Print",HAPI_Print); jvm.register_host("Gets",HAPI_Gets); // MainFunction is a global variable which contains a pointer to the script main function jvm_var main_fnc = jvm.get_var(script,"MainFunction"); if (main_fnc.type != jvm_funcptr) { // variable not found or not initialized with a function pointer cerr << "An error occurred while accessing global variable MainFunction!" << endl; jvm.release(); return -1; } int funcindex = main_fnc.func(); // extract function index from the variable // call script main function int ret = jvm.call_func(script,funcindex); // return value is cast to int // calls can also be made by function name (but function must be exported) // ret contains script return code if (ret != 0) { cerr << "Script returned error code: " << ret << endl; jvm.release(); return -1; } else cout << "Script executed succesfully!" << endl; jvm.release(); // free virtual machine return 0; }