我正在使用 OpenGL 实现重构我的 V8,但遇到了执行上下文的问题。
概念如下:
V8GL::initialize()
此方法初始化上下文和全局模板。它还使用 glut 的上下文,因为有几个循环也在运行,这些循环也暴露在 JS 上下文中。(例如glut.mainLoop()
)V8GL::execute(context, source, url)
此方法主要在给定上下文中执行字符串。我认为它必须是这种方式,以便以后使用间隔/超时来隔离使用。
什么不起作用:
V8GL::initialize()
还附加内置的 JavaScript 文件并执行它们。这工作得很好。
简化代码:
V8GL::initialize(...) {
v8::Persistent<v8::Context> context = v8::Context::New(NULL, globalTemplate);
v8::Context::Scope context_scope(context);
// cached for glut mainLoop etc.
GlutFactory::context_ = v8::Persistent<v8::Context>::New(context);
execute(context, v8::String::New(...script content...), v8::String::New(...script url path to show for exception stacktraces...);
// after all the stuff was dispatched to the global context, I want to cache the global object for later usage.
v8gl::global = v8::Persistent<v8::Object>::New(context->Global());
context->DetachGlobal();
context.Dispose();
}
V8GL::execute(context, source, filename) {
v8::HandleScope scope;
// Previously, I had v8::Context::Scope(context) in here.
v8::Local<v8::Script> script = v8::Script::Compile(source, filename);
}
问题:
那是初始化。这很好用,所以我自己的库中的东西可以在 JavaScript 执行中使用。但是我想执行另一个文件,该文件是通过参数传递的。所以 main.cppmain()
看起来像这样。
int main(...) {
v8gl::V8GL::initialize(&argc, argv); // argc and argv required for glut.
v8::HandleScope scope;
// This doesn't work:
// v8::Local<v8::Context> context = v8::Context::GetCurrent();
// You can't pass NULL as second parameter, so what then?
v8::Context::New(NULL, v8::ObjectTemplate::New(), v8gl::global);
// In here, all globals are lost. Why?
v8gl::V8GL::execute(context, source, filepath);
}
问题:
- 我是否必须缓存 global 的 objectTemplate 以供使用
v8::Context::New()
? - global_object 必须是持久的还是本地的?
- 我怎样才能重复使用它?
DetachGlobal()
and东西只适用于单一的ReattachGlobal()
上下文,而不是多个上下文。我的案例需要多个上下文。