V8编程入门

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

Hello World

让我们看一个Hello World的示例,它将一个字符串参数作为JavaScript语句,执行JavaScript代码,并将结果打印到控制台。

  1. int main(int argc, char* argv[]) {  
  2.   
  3.   // Create a string containing the JavaScript source code.  
  4.   String source = String::New("'Hello' + ', World'");  
  5.   
  6.   // Compile the source code.  
  7.   Script script = Script::Compile(source);  
  8.   
  9.   // Run the script to get the result.  
  10.   Value result = script->Run();  
  11.   
  12.   // Convert the result to an ASCII string and print it.  
  13.   String::AsciiValue ascii(result);  
  14.   printf("%s\n", *ascii);  
  15.   return 0;  
  16. }  

要真正使用V8引擎运行此示例,您还需要添加句柄(handle),句柄作用域(handle scope),以及上下文(context):

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

如下的例子和上面的相同,但是它包含句柄(handle),作用域(scope),上下文(context),它也包含命名空间和V8头文件:

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

运行示例

按照下列步骤来运行示例程序:

    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! 。
posted @ 2014-03-29 17:34  腐烂的翅膀  阅读(1698)  评论(0编辑  收藏  举报