使用C++调用V8

文章来自:https://developers.google.com/v8/get_started


Hello World

下面的C++代码将调用V8的解释器,运行一段js代码。

#include <v8.h>

using namespace v8;

int main(int argc, char* argv[]) {
  // Get the default Isolate created at startup.
  Isolate* isolate = Isolate::GetCurrent();

  // Create a stack-allocated handle scope.
  HandleScope handle_scope(isolate);

  // Create a new context.
  Handle<Context> context = Context::New(isolate);

  // Here's how you could create a Persistent handle to the context, if needed.
  Persistent<Context> persistent_context(isolate, context);
  
  // 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();
  
  // The persistent handle needs to be eventually disposed.
  persistent_context.Dispose();

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


在V8中运行js代码,需要一个handles, handle scope和context:

  • handle 是指向js对象的指针。所有的v8对象都关联到一个handle指针,这个指针被V8的垃圾收集器使用;
  • scope可以认为是一组handle的容器。当你使用完这些handle后,你可以简单的删除这个scope,而不必删除每个handle;
  • context是一个可执行环境,可以将js代码分离的运行在不同的v8实例中。要运行js代码,必须创建一个context。

运行

1. 下载和编译V8download and build instructions.

2. 拷贝上面的代码,并存储到一个文本文件hello_world.cpp

3. 编译hello_world.cpp,如在linux上可以这样:

g++ -Iinclude hello_world.cc -o hello_world out/x64.release/obj.target/tools/gyp/libv8_{base,snapshot}.a -lpthread

4. 运行hello_world


在window运行(这部分是本人原创)

注意,我是用VS2010编译和运行的。 v8的可执行库从 http://download.csdn.net/detail/doon/6442033下载

下面是步骤:

1. 创建一个VS2010 控制台工程,注意,以空项目的方式创建;

2. 添加一个新文件: hello_world.cpp,并把上面的代码拷贝到该文件中,保存;

3. 下载v8_sdk.rar ,解压并放在一个指定位置

4. 打开工程属性页,配置C++头文件:( <path>\v8_sdk\include)


5. 配置lib库的路径(<path>\v8_sdk\lib)



6. 增加库

v8_base.ia32.lib
v8_nosnapshot.ia32.lib
v8_snapshot.lib
icui18n.lib
icuuc.lib
Ws2_32.lib
winmm.lib



7. 编译解决方案并运行。



你可能感兴趣的:(使用C++调用V8)