[V8] 在C++中应用Google Chrome脚本引擎——V8

谁不想知道虚拟机是怎样工作的?不过,比起自己写一个虚拟机,更好的办法是使用大公司的产品。在这篇文章中,我将向你介绍怎样在你的程序中使用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引擎的简单例子: 

  1. #include <v8.h> 
  2. using namespace v8;
  3. int main(int argc, char* argv[]) {
  4.   // Create a stack-allocated handle scope. 
  5.   HandleScope handle_scope;
  6.   // Create a new context. 
  7.   Handle<Context> context = Context::New();
  8.   // Enter the created context for compiling and 
  9.   // running the hello world script.
  10.   Context::Scope context_scope(context);
  11.   // Create a string containing the JavaScript source code. 
  12.   Handle<String> source = String::New("'Hello' + ', World!'");
  13.   // Compile the source code. 
  14.   Handle<Script> script = Script::Compile(source);
  15.   // Run the script to get the result. 
  16.   Handle<Value> result = script->Run();
  17.   // Convert the result to an ASCII string and print it. 
  18.   String::AsciiValue ascii(result);
  19.   printf("%s ", *ascii);
  20.   return 0;
  21. }

好了,不过这还不能说明怎样让我们控制脚本中的变量和函数。

全局模型(The Global Template)

首先,我们需要一个全局模型来掌控我们所做的修改:

  1. v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();

这里建立了一个新的全局模型来管理我们的上下文(context)和定制。在V8里,每个上下文是分开的,它们有自己的全局模型。一个上下文就是一个独立的执行环境,相互之间没有关联,JavaScript运行于其中一个实例之中。

自定义函数

接下来,我们加入一个名为"plus"的自定义函数:

  1. // plus function implementation - Add two numbers
  2. v8::Handle<v8::Value> Plus(const v8::Arguments& args)
  3.     unsigned int A = args[0]->Uint32Value();
  4.     unsigned int B = args[1]->Uint32Value();
  5.     return v8_uint32(A +  B);
  6. //...
  7. //associates plus on script to the Plus function
  8. 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会用它来存取脚本中的变量。

  1. global->SetAccessor(v8::String::New("x"), XGetter, XSetter);

这行代码关联名称"x"到XGetterXSetter函数。这样在脚本中每次读取到"x"变量时都会调用XGetter,每次更新"x"变量时会调用XSetter。下面是这两个函数的代码: 

  1. //the x variable!
  2. int x;
  3. //get the value of x variable inside javascript
  4. static v8::Handle<v8::Value> XGetter( v8::Local<v8::String> name, 
  5.                   const v8::AccessorInfo& info) {
  6.   return  v8::Number::New(x);
  7. }
  8. //set the value of x variable inside javascript
  9. static void XSetter( v8::Local<v8::String> name, 
  10.        v8::Local<v8::Value> value, const v8::AccessorInfo& info) {
  11.   x = value->Int32Value();
  12. }

XGetter里我们把"x"转换成V8喜欢的数值类型。XSetter里,我们把传入的参数转换成整数,Int32Value是基本类型转换函数的一员,还有NumberValue对应doubleBooleanValue对应bool,等。

现在,我们可以为字符串做相同的操作: 

  1. //the username accessible on c++ and inside the script
  2. char username[1024];
  3. //get the value of username variable inside javascript
  4. v8::Handle<v8::Value> userGetter(v8::Local<v8::String> name, 
  5.            const v8::AccessorInfo& info) {
  6.     return v8::String::New((char*)&username,strlen((char*)&username));
  7. }
  8. //set the value of username variable inside javascript
  9. void userSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
  10.     const v8::AccessorInfo& info) {
  11.     v8::Local<v8::String> s = value->ToString();
  12.     s->WriteAscii((char*)&username);
  13. }

对于字符串,有一点点不同,"userGetter"和XGetter做的一样,不过userSetter要先用ToString方法取得内部字符串,然后用WriteAscii函数把内容写到我们指定的内存中。现在,加入存取器: 

  1. //create accessor for string username
  2. global->SetAccessor(v8::String::New("user"),userGetter,userSetter); 

打印输出

"print"函数是另一个自定义函数,它通过"printf"输出所有的参数内容。和之前的"plus"函数一样,我们要在全局模型中注册这个函数: 

  1. //associates print on script to the Print function
  2. global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); 

实现"print"函数

  1. // The callback that is invoked by v8 whenever the JavaScript 'print'
  2. // function is called. Prints its arguments on stdout separated by
  3. // spaces and ending with a newline.
  4. v8::Handle<v8::Value> Print(const v8::Arguments& args) {
  5.     bool first = true;
  6.     for (int i = 0; i < args.Length(); i++)
  7.     {
  8.         v8::HandleScope handle_scope;
  9.         if (first)
  10.         {
  11.             first = false;
  12.         }
  13.         else
  14.         {
  15.             printf(" ");
  16.         }
  17.         //convert the args[i] type to normal char* string
  18.         v8::String::AsciiValue str(args[i]);
  19.         printf("%s", *str);
  20.     }
  21.     printf(" ");
  22.     //returning Undefined is the same as returning void...
  23.     return v8::Undefined();
  24. }

这里,为每个参数都构建了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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值