zoukankan      html  css  js  c++  java
  • Google V8编程详解(二)HelloWorld

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

    上一章讲到了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 ", *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文件内容为:

    [javascript] view plaincopyprint?
     
    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的,在后面章节将做详细的分析。


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

  • 相关阅读:
    KMP
    1. Android Studio阅读源码
    疑难杂症
    队列
    方法和数组
    基本语法
    MySQL数据库创建
    MySQL安装
    Python--爬虫之(斗图啦网站)图片爬取
    Linux网络编程之基础概念
  • 原文地址:https://www.cnblogs.com/MingZznet/p/3231084.html
Copyright © 2011-2022 走看看