我对QuickJS很陌生,我正在尝试制作一个基本程序来加载并运行一个脚本。
下面是加载并运行脚本的代码片段:
auto jsr = shared_ptr<JSRuntime>(JS_NewRuntime(), JS_FreeRuntime);
for (auto &f : files){
auto ctx = shared_ptr<JSContext>(JS_NewContext(jsr.get()), JS_FreeContext);
js_init_module_os(ctx.get(), "os");
js_init_module_std(ctx.get(), "std");
size_t bufLen = 0;
auto buf = js_load_file(ctx.get(), &bufLen, f.c_str());
cout << "Starting Evaluation\n";
JS_Eval(ctx.get(), (char*)buf, bufLen, f.c_str(), JS_EVAL_TYPE_MODULE);
cout << "Ending Evaluation\n";
}下面是我正在运行的脚本:
import {sleep} from 'os';
for (let i = 0; i < 100; i++)
{
print("First Sleep: "+i);
sleep(1000);
}当它执行时,我在“启动评估”之后得到一个分段错误,所以我知道它发生在JS_Eval调用中。
我可以使用qjs实用程序很好地运行这个脚本。看看qjs.c,与我的程序相比,qjs完成了相当多的额外处理。然而,这是非常复杂的,我不明白与qjs相比,我做错了什么。
以前有没有人遇到过这样的问题?
谢谢
发布于 2022-10-08 02:27:22
我最近写了一个带有内置quickjs的“最小”c程序,并遇到了类似的问题。下面是我最后需要添加的几行代码,以使工作正常进行:
js_std_init_handlers(runtime);:不确定?但是没有它的分段故障js_std_add_helpers(ctx, 0, 0);:添加print()有了这些行,除了上面的行之外,我还可以执行您的脚本。
这是我的c程序
// gcc mvp.c -o mvp -lm -Lquickjs -Iquickjs -lquickjs
#include "quickjs-libc.h"
#include "quickjs.h"
int main(const int argc, const char **argv) {
JSRuntime *runtime = JS_NewRuntime();
js_std_init_handlers(runtime);
// JS_SetModuleLoaderFunc(runtime, NULL, js_module_loader, NULL);
JSContext *ctx = JS_NewContext(runtime);
js_init_module_std(ctx, "std");
js_init_module_os(ctx, "os");
js_std_add_helpers(ctx, 0, 0);
size_t buf_len;
uint8_t *buf = js_load_file(ctx, &buf_len, argv[1]);
JSValue result = JS_Eval(ctx, buf, buf_len, argv[1], JS_EVAL_TYPE_MODULE);
// js_std_loop(ctx);
}我上面已经注释掉的两行代码,对于示例脚本来说是不必要的:
JS_SetModuleLoaderFunc:如果我导入了任何非本机模块,就必须这样做。js_std_loop:“事件循环”,是承诺/超时工作所必需的https://stackoverflow.com/questions/72665281
复制相似问题