#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() = 1
Handle<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的用法
v8学习---使用内部字段给js添加全局变量
最新推荐文章于 2024-11-08 12:41:58 发布