基于V8 引擎开发(1)

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



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

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


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

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



int main(int argc, char* argv[]) {

  // Create a string containing the JavaScript source code.
  String source = String::New("'Hello' + ', World'");

  // Compile the source code.
  Script script = Script::Compile(source);
  
  // Run the script to get the result.
  Value result = script->Run();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf("%s\n", *ascii);
  return 0;
}


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

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

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

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


运行 例子:

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




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值