Google V8编程详解(二)HelloWorld

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

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

#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;
}

我的目录结构如下:


编译运行:

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

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

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

  Handle<String> source = String::New("'Hello' + ', World!'");
看到这句话,其实就是在加载一个js文件了。只不过这个js文件内容为:

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

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

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


版权申明:
转载文章请注明原文出处,任何用于商业目的,请联系本人:[email protected]


猜你喜欢

转载自blog.csdn.net/feiyinzilgd/article/details/8248448