本文最新地址:http://exbrowser.com/?p=481
本文档介绍了V8的一些关键概念,提供了helloworld例子用于开始使用V8的代码。
内容
- 读者
- Hello World
- 运行例子程序
读者
本文档用于想嵌入V8引擎到自己C++应用的C++开发者。
Hello World
让我们一起看看Hello World例子,这个例子采用字符串作为参数的表达式,并执行JavaScript代码在标准的输出设备上打印结果。
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;
}
在V8中实际运行这个例子,您需要增加句柄、作用域句柄和上下文对象。
- 一个句柄就是指向对象的指针。所有的V8对象的访问都通过句柄,这是V8垃圾回收机制所要求的。
- 作用域可认为容纳了任意数量的句柄,当您完成使用这些句柄时,不必单个删除每个句柄,仅删除他们的作用域即可。
- 上下文是分离的、无关的JavaScript代码运行在单一实例的V8中的执行环境。您必须显示指定执行javascript的上下文。
下面例子除了增加了句柄、上下文和作用域对象外与上例相同,同时包含了命名空间和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::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 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;
}
运行例子
遵循下面的步骤执行例子:
- 下载V8源码和根据"downloading and build instructions"文档编译V8。
- 从上一节中(第二个代码片段),拷贝完整的源码,粘贴到您的文本编辑器并另存到编译V8期间创建的V8目录,文件名是hello_world.cpp。
- 编译hello_world.cpp连接到libv8.a库(在编译v8过程中生成的)。例如,在Linux使用GNU编译器g++ -Iinclude hello_world.cpp -o hello_world libv8.a -lpthread
- 在命令行里运行hello_world可执行程序。例如,在Linux,依旧在V8目录,在命令行中输入./hello_world。
- 您将看到"Hello, World!"。
当然这是一个非常简单的例子而且您想做更多想执行脚本输出字符串的工作是可能的。更多信息见”嵌入者的手册“。

本文介绍V8 JavaScript引擎的关键概念及如何在C++应用中嵌入V8。通过一个Hello World的例子,展示了创建JavaScript代码、编译及运行的过程。此外还详细解释了句柄、作用域和上下文对象的概念。
2649

被折叠的 条评论
为什么被折叠?



