基于V8 引擎开发(1)

                                                            csdn    lidp    http://blog.csdn.net/perfectpdl



本文介绍了一些V8关键概念,同时提供了一个在v8提供的接口上的hello world 例子。

本文介绍的开发模式是采用C++语言,把V8 js引擎嵌入到c++应用程序中。


在 v8介绍一文中 提过js引擎的目的是解析 js代码,编译,执行。

下面的例子中把hell world做为js代码执行并输出结果到屏幕:



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


为了执行以上代码,还需要添加 句柄(handler),句柄范围(handler scope)以及上下文(context)。

  • 句柄就是一个指向对象的指针,所有v8对象的访问都通过句柄
  • 句柄范围可以被认为是一个句柄的容器,当你不想释放句柄资源时,可以最后通过释放句柄范围来释放所有句柄资源。
  • 上下文是一个执行环境,一个上下文把分离的,无关的js代码集成在一起,作为一个v8实例执行。

下面的代码包含了 句柄,句柄范围,上下文版本:

[html]  view plain copy print ?
  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代码,编译 ,参照前文 
2. 把上面的代码拷贝到文件 hello_v8.cpp,放到v8源码目录下

3. 编译 hello-v8.cpp , 在linux下面用gcc编译命令如下:
g++ -Iinclude hello_v8.cpp -o hello_world libv8.a -lpthread
4 .上面的libv8.a为 编译v8后生成的静态库,执行 生成的可执行程序:
 ./hello_world



你可能感兴趣的:(基于V8 引擎开发(1))