v8学习---使用内部字段给js添加全局变量

来源:互联网 发布:男生喜欢手办恶心知乎 编辑:程序博客网 时间:2024/05/17 06:40
#include <v8.h>#include <iostream>using namespace v8;void Setter(Local<String> property, Local<Value> value,const PropertyCallbackInfo<void>& info){Local<Object> self = info.Holder();Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));void* ptr = wrap->Value();static_cast<int*>(ptr)[0] = value->Int32Value();}void Getter(Local<String> property, const PropertyCallbackInfo<Value>& info){Local<Object> self = info.Holder();Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));void* ptr = wrap->Value();info.GetReturnValue().Set(static_cast<int*>(ptr)[0]);}int main(){int age = 9527;Isolate* isolate = Isolate::GetCurrent();HandleScope handleScope(isolate);Handle<ObjectTemplate> global = ObjectTemplate::New();//所有由global这个模板产生的Object都有一个内部的字段global->SetInternalFieldCount(1);global->SetAccessor(String::New("age"), Getter, Setter);Handle<Context> context = Context::New(isolate, NULL, global);Context::Scope context_scope(context); //global模板所产生的Object是context->Global()->GetPrototype();//而不是context->Global(),所以context->InternalFieldCount() == 0 而//context->Global()->GetPrototype()->InternalFieldCount() = 1Handle<Object> global_proto = Handle<Object>::Cast(context->Global()->GetPrototype());global_proto->SetInternalField(0, External::New(&age));Handle<Script> script = Script::Compile(String::New("++age"));Handle<Value> value = script->Run();String::AsciiValue ascii(value);printf("%s\n", *ascii);return 0;}
留意其中Local<External>, External::New, SetInternalFieldCount,SetInternalField,GetInternalField的用法
原创粉丝点击