谁不想知道虚拟机是怎样工作的?不过,比起自己写一个虚拟机,更好的办法是使用大公司的产品。在这篇文章中,我将向你介绍怎样在你的程序中使用V8——谷歌浏览器(Chrome)所使用的开源JavaScript引擎。
原文地址:http://www.codeproject.com/KB/library/Using_V8_Javascript_VM.aspx
介绍
谁不想知道虚拟机是怎样工作的?不过,比起自己写一个虚拟机,更好的办法是使用大公司的产品。在这篇文章中,我将介绍如何在你的程序中使用V8——谷歌浏览器(Chrome)所使用的开源JavaScript引擎。
背景
这里的代码使用V8作为嵌入库来执行JavaScript代码。要取得库源码和其它信息,可以浏览V8开发者页面。想有效地应用V8,你需要了解C/C++和JavaScript。
使用
我们来看看演示中有哪些东西:
- 如何使用V8库API来执行JavaScript脚本。
- 如何存取脚本中的整数和字符串。
- 如何建立可被脚本调用的自定义函数。
- 如何建立可被脚本调用的自定义类。
首先,我们一起了解一下怎样初始化V8。这是嵌入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 ", *ascii);
- return 0;
- }
好了,不过这还不能说明怎样让我们控制脚本中的变量和函数。
全局模型(The Global Template)
首先,我们需要一个全局模型来掌控我们所做的修改:
- v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
这里建立了一个新的全局模型来管理我们的上下文(context)和定制。在V8里,每个上下文是分开的,它们有自己的全局模型。一个上下文就是一个独立的执行环境,相互之间没有关联,JavaScript运行于其中一个实例之中。
自定义函数
接下来,我们加入一个名为"plus"的自定义函数:
- // plus function implementation - Add two numbers
- v8::Handle<v8::Value> Plus(const v8::Arguments& args)
- {
- unsigned int A = args[0]->Uint32Value();
- unsigned int B = args[1]->Uint32Value();
- return v8_uint32(A + B);
- }
- //...
- //associates plus on script to the Plus function
- global->Set(v8::String::New("plus"), v8::FunctionTemplate::New(Plus));
自定义函数必须以const v8::Arguments&
作为参数并返回v8::Handle<v8::Value>
。我们把这个函数加入到模型中,关联名称"plus"到回调Plus。现在,在脚本中每次调用"plus",我们的Plus函数就会被调用。这个函数只是返回两个参数的和。
现在我们可以在JavaScript里使用这个自定义函数了:
plus( 120 , 44 );在脚本里也可以得到函数的返回值:
x = plus( 1 , 2 ); if ( x == 3 ){ // do something important here! }访问器(Accessor)——存取脚本中的变量
现在,我们可以建立函数了...不过如果我们可以在脚本外定义一些东西岂不是更酷?Let's do it! V8里有个东东称为存取器(Accessor),使用它,我们可以关联一个名称到一对Get/Set函数上,V8会用它来存取脚本中的变量。
- global->SetAccessor(v8::String::New("x"), XGetter, XSetter);
这行代码关联名称"x
"到XGetter
和XSetter
函数。这样在脚本中每次读取到"x"变量时都会调用XGetter
,每次更新"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喜欢的数值类型。XSetter
里,我们把传入的参数转换成整数,Int32Value是基本类型转换函数的一员,还有NumberValue
对应double
、BooleanValue
对应bool
,等。
现在,我们可以为字符串做相同的操作:
- //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);
打印输出
"print
"函数是另一个自定义函数,它通过"printf
"输出所有的参数内容。和之前的"plus
"函数一样,我们要在全局模型中注册这个函数:
- //associates print on script to the Print function
- global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
实现"print"函数
- // The callback that is invoked by v8 whenever the JavaScript 'print'
- // function is called. Prints its arguments on stdout separated by
- // spaces and ending with a newline.
- v8::Handle<v8::Value> Print(const v8::Arguments& args) {
- bool first = true;
- for (int i = 0; i < args.Length(); i++)
- {
- v8::HandleScope handle_scope;
- if (first)
- {
- first = false;
- }
- else
- {
- printf(" ");
- }
- //convert the args[i] type to normal char* string
- v8::String::AsciiValue str(args[i]);
- printf("%s", *str);
- }
- printf(" ");
- //returning Undefined is the same as returning void...
- return v8::Undefined();
- }
这里,为每个参数都构建了v8::String::AsciiValue
对象:数据的char*表示。通过它,我们就可以把所有类型都转换成字符串并打印出来。
JavaScript演示
在演示程序里,我们有一个简单的JavaScript脚本,调用了迄今为止我们建立的所有东西:
print( " begin script" );print(script executed by + user); if ( user == " John Doe" ){ print( " \tuser name is invalid. Changing name to Chuck Norris" ); user = " Chuck Norris" ;}print( " 123 plus 27 = " + plus( 123 , 27 ));x = plus( 3456789 , 6543211 );print( " end script