Created
June 15, 2020 02:02
-
-
Save tek-nishi/7154bad87d838d5f4e89e31d5a0f918c to your computer and use it in GitHub Desktop.
QuickJS test code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <fstream> | |
#include <quickjs.h> | |
std::string readTextFile(const std::string& path) | |
{ | |
std::ifstream ifs(path); | |
return std::string(std::istreambuf_iterator<char>(ifs), | |
std::istreambuf_iterator<char>()); | |
} | |
int main() | |
{ | |
JSRuntime *rt = JS_NewRuntime(); | |
JSContext *ctx = JS_NewContext(rt); | |
auto text = readTextFile("test.js"); | |
if (JS_IsException(JS_Eval(ctx, text.c_str(), text.size(), "<input>", JS_EVAL_FLAG_STRICT))) | |
{ | |
JS_FreeContext(ctx); | |
JS_FreeRuntime(rt); | |
return -1; | |
} | |
JSValue global = JS_GetGlobalObject(ctx); | |
JSValue func = JS_GetPropertyStr(ctx, global, "update"); | |
for (int i = 0; i < 3; ++i) | |
{ | |
JSValue jsResult = JS_Call(ctx, func, global, 0, nullptr); | |
int32_t result; | |
JS_ToInt32(ctx, &result, jsResult); | |
std::cout << result << "\n"; | |
} | |
JSValue used[] = { func, global }; | |
for (int i = 0; i < std::size(used); ++i) | |
{ | |
JS_FreeValue(ctx, used[i]); | |
} | |
JS_FreeContext(ctx); | |
JS_FreeRuntime(rt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment