Google V8编程详解(二)HelloWorld

来源:互联网 发布:手机淘宝如何申请试用 编辑:程序博客网 时间:2024/06/05 08:40

上一章讲到了V8的编译和安装,这一章开始从一个demo着手。

这里选用了官方文档的一个非常简洁的HelloWorld.cc,代码如下:

 

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


我的目录结构如下:

 

编译运行:

 

  1. g++ -I../include helloworld.cc  -o helloworld -lpthread -lv8  
  1. ./helloworld  


就可以在屏幕上看到输出结果了。

 

看到demo上有一些Context,Scope,Value等等,先不要慌张,其实就是V8的一些基本 数据类型,这些在后面会逐个一一讲到。                                                                                    

 

  1. Handle<String> source = String::New("'Hello' + ', World!'");  

看到这句话,其实就是在加载一个js文件了。只不过这个js文件内容为:

 

 

  1. 'Hello' + ', World!'  

那么这里,source就已经是加载过的js文件字符串内容了,接下来V8需要对js进行编译解释。

 

  1. Handle<Script> script = Script::Compile(source);  
  2. Handle<Value> result = script->Run();  

 

最后就是JS的执行了。这里虽然只有简单的几个语句,但是V8对于JS的编译和运行做了很多很复杂的操作。关于V8是如何编译和运行JS的,在后面章节将做详细的分析。


版权申明:

转自http://www.cnblogs.com/MingZznet/p/3231084.html

0 0