How to get ObjectTemplate in a previous created context?

25 views
Skip to first unread message

Jian Guo

unread,
Jun 1, 2019, 1:43:56 AM6/1/19
to v8-users
I want to wrap a javascript class in v8 embedded.

v8::Persistent<v8::Context> persistentContext;
v8::Isolate *pIsolate;
void init() {
v8::V8::InitializeICU();
platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(&(*platform.get()));
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
pIsolate = v8::Isolate::New(create_params);  
 auto ft = v8::FunctionTemplate::New(pIsolate);
    ft
->SetClassName(v8::String::NewFromUtf8(
pIsolate, "MyClass"));
    ft
->ReadOnlyPrototype();
    ft
->SetCallHandler(MyClass::constructorCallback);
    ft
->SetLength(1);
    v8
::Eternal<v8::FunctionTemplate> v8MyClassConstructor(
pIsolate, ft);
    auto global_template = v8::ObjectTemplate::New(
pIsolate);
    global_template->Set(v8::String::NewFromUtf8(pIsolate, "MyClass"), v8MyClassConstructor.Get(pIsolate));

   
// Enter the context for compiling and running the hello world script.
    v8
::Local<v8::Context> context = v8::Context::New(
pIsolate, nullptr, global_template);
    persistentContext
.Reset(
pIsolate
, context);
}




In my code, after init() being called, I want to wrap more native class to the previous context, what should I do? I want something like:


void bindClass() {
   
auto ctx = persistentContext.Get(pIsolate);
   
auto global = ctx->GetGlobalObjectTemplate(); // No such function, trying to get global_template variable from init() method
   
auto ft = v8::FunctionTemplate::New(pIsolate);
  ft->SetClassName(v8::String::NewFromUtf8(pIsolate, "Foo"));
 
// set up another class called "Foo"
 
global->Set(v8::String::NewFromUtf8(pIsolate, "Foo"), ft));
   
}


void main() {
       init
();
       
// some code here...
       bindClass
();   // bind more class to global later...
}


Besides, I am puzzled with the global_template concept here, as it is mentioned in the https://v8.dev/docs/embed#templates sample code:

// Create a template for the global object and set the
// built-in global functions.
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
global->Set(String::NewFromUtf8(isolate, "log"),
            FunctionTemplate::New(isolate, LogCallback));

// Each processor gets its own context so different processors
// do not affect each other.
Persistent<Context> context = Context::New(isolate, NULL, global);


Ben Noordhuis

unread,
Jun 1, 2019, 8:17:58 AM6/1/19
to v8-users
Once the global object is created, it's created - modifying the
ObjectTemplate post hoc won't do anything.

You can still add properties ad hoc through
context->Global()->Set(...) but they won't show up in other contexts,
of course.
Reply all
Reply to author
Forward
0 new messages