v8學習---使用內部字段給js添加全局變量

#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的用法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章