使用V8——Google Chrome 的 JavaScript 引擎
Posted on 2008-10-18 16:24 sufan 閱讀(5736) 評論(3) 編輯 收藏 引用 所屬分類: 翻譯(希望能夠與大家多交流,一起學習V8。)
原文地址:http://www.codeproject.com/KB/library/Using_V8_Javascript_VM.aspx
本文代碼下載:demo
簡介
有誰從沒好奇過虛擬機是怎樣工作的?但是,和自己做一個虛擬機比起來,你若是能使用一個大公司做的虛擬機,并把重點放在提高VM的速度上則更為實際。本文中,我將向你介紹怎樣在應用程序開發中使用 Google Chrome 瀏覽器內置的開源 JavaScript 引擎——V8。
環境
本文提供的代碼使用 V8 作為內含的庫來執行 JavaScript 代碼。你可以到 V8 developer page 上去獲取 V8 庫的源代碼及其他相關信息。你還需要了解C/C++和 JavaScript 知識,以便更加有效的使用V8庫。
代碼的使用
讓我們來看看 demo 中所含內容。它向我們展示了:
怎樣使用 V8 的API來執行 JavaScript 程序。
怎樣訪問腳本中整數和字符串。
怎樣創建能夠在腳本中被調用的函數。
怎樣創建能夠在腳本中被調用的C++類。
首先,讓我們來了解一下怎樣初始化 V8 API,先來看看下面這個在C++中使用V8的例子:
#include <v8.h>
using namespace v8;
int main(int argc, char* argv[])
{
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Handle<Context> context = Context::New();
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Handle<String> source = String::New("'Hello' + ', World!'");
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
using namespace v8;
int main(int argc, char* argv[])
{
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Handle<Context> context = Context::New();
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Handle<String> source = String::New("'Hello' + ', World!'");
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
雖然以上的代碼并沒有向我們解釋如何在腳本中控制變量和函數,不過看起來腳本的確開始起作用了……但是我們仍然需要設法了解這方面的知識,以便使用我們自己的函數來控制腳本中的特殊動作。