V8编程入门

原文:

http://www.grati.org/?p=336

 

译自:http://code.google.com/intl/zh-CN/apis/v8/get_started.html 转载请注明译文链接。


本文档介绍了V8引擎的一些关键概念,并提供了例子hello world指引你入门。

读者

本文件的目标读者是想要将V8JavaScript引擎嵌入C++应用的程序员。

Hello World

让我们看一个Hello World的示例,它将一个字符串参数作为JavaScript语句,执行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引擎运行此示例,您还需要添加句柄(handle),句柄作用域(handle scope),以及上下文(context):

  • 句柄(handle)是一个指向对象的指针。由于V8垃圾回收器的工作原理,所有的V8对象都是使用句柄访问的。
  • 作用域(scope)可以被当做一个容器,可以容纳任何数量的句柄(handle)。当您完成对句柄的操作,你可以简单地删除它们的范围(scope)而不用删除每一个单独的句柄。
  • 上下文(context)是一个执行环境,允许JavaScript代码独立的运行在一个V8引擎实例中。要执行任何JavaScript代码,您必须显式的指定其运行的上下文。

如下的例子和上面的相同,但是它包含句柄(handle),作用域(scope),上下文(context),它也包含命名空间和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 = 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();

  // 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引擎的源代码并依据下载构建指南编译V8 。
  2. 复制上一节中的代码(第二部分),粘贴到您最喜爱的文本编辑器,其命名为hello_world.cpp并保存在构建V8引擎时创建的目录中。
  3. 编译hello_world.cpp,并链接编译V8时生成的库文件libv8.a。例如,在Linux上使用GNU编译器:
    g++ -Iinclude hello_world.cpp -o hello_world libv8.a -lpthread
  4. 在终端中运行hello_world可执行文件。
    例如,在Linux上,还是在V8引擎的目录中,在命令行键入以下内容:
    ./hello_world
  5. 你将会看到Hello, World!

当然,这是一个简单的例子,你想要做的肯定不仅是执行字符串脚本这么简单!欲了解更多信息,请参阅V8嵌入指南


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值