如何使用多个v8 :: Context s正确地重用global_object?

Chr*_*ens 5 c++ v8 embedded-v8

我正在使用OpenGL实现重构我的V8并且遇到了执行上下文的问题.

这个概念如下:

  • V8GL::initialize() 此方法初始化上下文和全局模板.它还使用上下文来表示过剩,因为有几个循环运行,它们也暴露给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);

}
Run Code Online (Sandbox Code Playgroud)

问题:

那是初始化.这很好,所以我自己的库的东西在JavaScript执行中可用.但我想执行另一个文件,通过参数传递.所以main.cpp main()看起来像这样.

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);

}
Run Code Online (Sandbox Code Playgroud)

问题:

  • 我是否必须缓存全局的objectTemplate以供使用v8::Context::New()
  • global_object必须是持久的还是本地的?
  • 我该如何重复使用它?在DetachGlobal()ReattachGlobal()东西只工作在具有单个上下文,不能与多个的.我的案例需要多个上下文.