Posted on 2008-10-19 23:35
sufan 閱讀(2984)
評論(1) 編輯 收藏 引用 所屬分類:
翻譯
訪問器——訪問腳本中的變量我們已經能夠在腳本中使用函數了。但如果我們能夠使用在腳本中定義的變量什么的豈不是更好?說做就做!V8有一個叫做訪問器的東西,有了它,我們就能通過名字來使用變量以及與它相關的兩個Set/Get函數,在運行腳本程序的時候,V8就是通過這兩個函數來實現對變量的訪問。
global->SetAccessor(v8::String::New("x"), XGetter, XSetter);
這行代碼就將“x”與“XGetter”和“XSetter”函數聯系在一起了。當V8需要得到“x”變量的值的時候,它就會去調用“XGetter”函數,相類似的,如果V8要更新“x”變量的值的時候,它調用的是“XSetter”函數。現在,我們的代碼成了:
//the x variable!
int x;
//get the value of x variable inside javascript
static v8::Handle<v8::Value> XGetter( v8::Local<v8::String> name,
const v8::AccessorInfo& info) {
return v8::Number::New(x);
}
//set the value of x variable inside javascript
static void XSetter( v8::Local<v8::String> name,
v8::Local<v8::Value> value, const v8::AccessorInfo& info) {
x = value->Int32Value();
}
在 XGetter 函數中,我們所要做的只是將“x”轉換成V8所能管理的 Number 類型的值。而在 XSetter 函數中,我們需要將這個作為參數傳過來的值轉換成一個整數。就像對應其基類型的函數,例如 NumberValue 之于 double,BooleanValue 之于 bool,等等。
對于 char * 類型的字符串,我們同樣有:
//the username accessible on c++ and inside the script
char username[1024];
//get the value of username variable inside javascript
v8::Handle<v8::Value> userGetter(v8::Local<v8::String> name,
const v8::AccessorInfo& info) {
return v8::String::New((char*)&username,strlen((char*)&username));
}
//set the value of username variable inside javascript
void userSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const v8::AccessorInfo& info) {
v8::Local<v8::String> s = value->ToString();
s->WriteAscii((char*)&username);
}
對于字符串,情況就有一點小小的變化了。userGetter 以 XGetter 相類似的方式創建了一個新字符串,但是 userSetter 首先需要使用 ToString 函數來訪問內部字符串緩沖區。然后,我們通過得到的指向內部字符串對象的指針,使用 WriteAscii 函數將字符串的內容寫到我們的緩沖區。最后添加相對應的訪問器,一切搞定!
//create accessor for string username
global->SetAccessor(v8::String::New("user"),userGetter,userSetter);