如何在今天的 v8 中包含另一个 js 文件?

How can I include another js file file in today's v8?

我找到了一个旧的答案,后来更新了here,但是我很难将这段代码适配到最新的(2020)V8 版本。

我遇到的困难很多:

  1. String::New 被删除,现在 String::NewFromUtf8Literal 需要一个 Isolate* isolate,我不知道如何传递给函数 Include,我应该在之前添加它吗const Arguments& args?
  2. Script::Compile 现在接受一个 Context 对象作为参数
  3. 而且我不知道最后两行代码放在哪里
    Handle<ObjectTemplate> global = ObjectTemplate::New();
    global->Set(String::New("include"), FunctionTemplate::New(Include));
    

-- 更新--

经过一些工作,我的代码像 this

然而,由于存在错误,它仍然无法编译:

  1. 似乎我无法从Persistent中得到Local,即使我已经使用了danijar's strategy。可能是因为我没有使用构造函数,但我认为我不能在这个函数范围内构造一个Persist。

    samples/import.cc:74:103: Error:cannot convert ‘v8::Local<v8::Context>’ to ‘v8::Context*’
       74 |     global_context = v8::Persistent<v8::Context, CopyablePersistentTraits<v8::Context>>::New(isolate, local_context);
          |                                                                                                       ^~~~~~~~~~~~~
          |                                                                                                       |
          |                                                                                                       v8::Local<v8::Context>
    
  2. 这里String::NewFromUtf8Literal有一些错误

    samples/import.cc:34:110: Error:‘static v8::Local<v8::String> v8::String::NewFromUtf8Literal(v8::Isolate*, const char*, v8::NewStringType, int)’ is private within this context
       34 |   Handle<String> source = String::NewFromUtf8Literal(args.GetIsolate(), buff, v8::NewStringType::kNormal, len);
          |   
    

I don't know how to pass to function Include, should I just add this before const Arguments& args?

不,你不能修改将从 JS 调用的函数的签名,但你不需要:FunctionCallbackInfo(它是 Arguments 的替代品)有一个GetIsolate() 方法。

Script::Compile takes a Context object as parameter now

既然你对此有疑问,我猜你只是对所有内容使用了一个上下文。只需将它存储在 v8::Persistent 中,并在需要时从中创建一个 v8::Local。 (目前,您还可以使用已弃用的 Isolate::GetCurrentContext(),但对于新编写的代码,我建议您不要这样做,因为将来您必须从它迁移时,只会为自己创造更多的工作.)

I don't know where to put the last two line codes

无论您在何处设置全局对象,在应用启动序列中的某处。

所有这些(以及更多)问题都可以通过研究 V8 项目维护的“shell”示例应用程序来回答:https://chromium.googlesource.com/v8/v8/+/master/samples/shell.cc。 特别是,它的 Load 功能几乎可以满足您的需求。