Posted on 2008-10-18 16:24
sufan 閱讀(5737)
評(píng)論(3) 編輯 收藏 引用 所屬分類:
翻譯
(希望能夠與大家多交流,一起學(xué)習(xí)V8。)
原文地址:http://www.codeproject.com/KB/library/Using_V8_Javascript_VM.aspx
本文代碼下載:demo
簡介
有誰從沒好奇過虛擬機(jī)是怎樣工作的?但是,和自己做一個(gè)虛擬機(jī)比起來,你若是能使用一個(gè)大公司做的虛擬機(jī),并把重點(diǎn)放在提高VM的速度上則更為實(shí)際。本文中,我將向你介紹怎樣在應(yīng)用程序開發(fā)中使用 Google Chrome 瀏覽器內(nèi)置的開源 JavaScript 引擎——V8。
環(huán)境
本文提供的代碼使用 V8 作為內(nèi)含的庫來執(zhí)行 JavaScript 代碼。你可以到 V8 developer page 上去獲取 V8 庫的源代碼及其他相關(guān)信息。你還需要了解C/C++和 JavaScript 知識(shí),以便更加有效的使用V8庫。
代碼的使用
讓我們來看看 demo 中所含內(nèi)容。它向我們展示了:
怎樣使用 V8 的API來執(zhí)行 JavaScript 程序。
怎樣訪問腳本中整數(shù)和字符串。
怎樣創(chuàng)建能夠在腳本中被調(diào)用的函數(shù)。
怎樣創(chuàng)建能夠在腳本中被調(diào)用的C++類。
首先,讓我們來了解一下怎樣初始化 V8 API,先來看看下面這個(gè)在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;
}
雖然以上的代碼并沒有向我們解釋如何在腳本中控制變量和函數(shù),不過看起來腳本的確開始起作用了……但是我們?nèi)匀恍枰O(shè)法了解這方面的知識(shí),以便使用我們自己的函數(shù)來控制腳本中的特殊動(dòng)作。