问题
I find an old anwser and later updates here, but it is hard for me to adapt this code to the latest(2020) V8 version.
There are many difficulties that I encounter:
String::Newis removed and now aString::NewFromUtf8Literalneeds anIsolate* isolatewhich I don't know how to pass to functionInclude, should I just add this beforeconst Arguments& args?Script::Compiletakes aContextobject as paramater now- And I don't know where to put the last two line codes
Handle<ObjectTemplate> global = ObjectTemplate::New(); global->Set(String::New("include"), FunctionTemplate::New(Include));
-- UPDATE --
After some work, I have my code like the this.
However, it still won't compile because of there errors:
Seems that I can't get a
Localfrom aPersistent, even I have used danijar's strategy. Maybe it is because I have not used the constructor, but I don't think I can construct a Persist here inside this function scope.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>There are some errors with
String::NewFromUtf8Literalheresamples/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); |
回答1:
I don't know how to pass to function Include, should I just add this before
const Arguments& args?
No, you can't modify the signature of functions that will be called from JS, but you don't need to: FunctionCallbackInfo (which is the replacement for Arguments) has a GetIsolate() method.
Script::Compiletakes aContextobject as parameter now
Since you're having a question about this, I'm guessing you're only using a single Context for everything. Just store it in a v8::Persistent, and create a v8::Local from it whenever you need it. (For the time being, you can also use the deprecated Isolate::GetCurrentContext(), but for newly written code I would advise against that, as you'd only create more work for yourself in the future when you have to migrate away from it.)
I don't know where to put the last two line codes
Wherever you're setting up the global object, somewhere in the startup sequence of your app.
All of these questions (and more) could be answered by studying the "shell" sample app that the V8 project maintains: https://chromium.googlesource.com/v8/v8/+/master/samples/shell.cc.
In particular, its Load function does pretty much what you want.
来源:https://stackoverflow.com/questions/64979842/how-can-i-include-another-js-file-file-in-todays-v8