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;
}
运行 例子:
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