Google V8编程详解(二)HelloWorld

转自http://blog.csdn.net/feiyinzilgd/article/details/8248448

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

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

 

[cpp]  view plain copy print ?
 
  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. }  


我的目录结构如下:

 

编译运行:

 

[html]  view plain copy print ?
 
  1. g++ -I../include helloworld.cc  -o helloworld -lpthread -lv8  
[html]  view plain copy print ?
 
  1. ./helloworld  


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

 

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

 

[cpp]  view plain copy print ?
 
  1. Handle<String> source = String::New("'Hello' + ', World!'");  

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

 

 

[javascript]  view plain copy print ?
 
  1. 'Hello' + ', World!'  

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

 

[cpp]  view plain copy print ?
 
  1. Handle<Script> script = Script::Compile(source);  
  2. Handle<Value> result = script->Run();  

 

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


版权申明:
转载文章请注明原文出处,任何用于商业目的,请联系本人:hyman_tan@126.com

 

转载于:https://www.cnblogs.com/MingZznet/p/3231084.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值