开始使用V8

本文介绍V8 JavaScript引擎的关键概念及如何在C++应用中嵌入V8。通过一个Hello World的例子,展示了创建JavaScript代码、编译及运行的过程。此外还详细解释了句柄、作用域和上下文对象的概念。

本文最新地址http://exbrowser.com/?p=481


本文档介绍了V8的一些关键概念,提供了helloworld例子用于开始使用V8的代码。

内容

  • 读者
  • Hello World
  • 运行例子程序

读者

本文档用于想嵌入V8引擎到自己C++应用的C++开发者。

Hello World

让我们一起看看Hello World例子,这个例子采用字符串作为参数的表达式,并执行JavaScript代码在标准的输出设备上打印结果。

int main(int argc, char* argv[]) {
 // Create a string containing the JavaScript source code.
 String source = String::New("'Hello' + ', World'");

 // Compile the source code.
 Script script = Script::Compile(source);

 // Run the script to get the result.
 Value result = script->Run();

 // Convert the result to an ASCII string and print it.
 String::AsciiValue ascii(result);

 printf("%s/n", *ascii);
 return 0;
}

在V8中实际运行这个例子,您需要增加句柄、作用域句柄和上下文对象。

  • 一个句柄就是指向对象的指针。所有的V8对象的访问都通过句柄,这是V8垃圾回收机制所要求的。
  • 作用域可认为容纳了任意数量的句柄,当您完成使用这些句柄时,不必单个删除每个句柄,仅删除他们的作用域即可。
  • 上下文是分离的、无关的JavaScript代码运行在单一实例的V8中的执行环境。您必须显示指定执行javascript的上下文。

下面例子除了增加了句柄、上下文和作用域对象外与上例相同,同时包含了命名空间和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.
 Persistent 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 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();

 // Dispose the persistent context.
 context.Dispose();

 // Convert the result to an ASCII string and print it.
 String::AsciiValue ascii(result);

 printf("%s/n", *ascii);

 return 0;

}

运行例子

遵循下面的步骤执行例子:

  1. 下载V8源码和根据"downloading and build instructions"文档编译V8。
  2. 从上一节中(第二个代码片段),拷贝完整的源码,粘贴到您的文本编辑器并另存到编译V8期间创建的V8目录,文件名是hello_world.cpp。
  3. 编译hello_world.cpp连接到libv8.a库(在编译v8过程中生成的)。例如,在Linux使用GNU编译器g++ -Iinclude hello_world.cpp -o hello_world libv8.a -lpthread
  4. 在命令行里运行hello_world可执行程序。例如,在Linux,依旧在V8目录,在命令行中输入./hello_world。
  5. 您将看到"Hello, World!"。

当然这是一个非常简单的例子而且您想做更多想执行脚本输出字符串的工作是可能的。更多信息见”嵌入者的手册“。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值