上篇在编译V8引擎,以及初步编译实例后,接下来认真分析一下V8所带的实例
v8-trunk\samples下面有3个例子
lineprocessor.cc
process.cc
shell.cc
首先从shell.cc入手
1:编译
g++ -I /usr/include/v8 shell.cc -o shell.exe /usr/test/libv8.so -lpthread
编译shell.cc为可执行文件
2:分析
定义函数包括:
v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate);
void RunShell(v8::Handle<v8::Context> context);
int RunMain(v8::Isolate* isolate, int argc, char* argv[]);
bool ExecuteString(v8::Isolate* isolate,
v8::Handle<v8::String> source,
v8::Handle<v8::Value> name,
bool print_result,
bool report_exceptions);
void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
void Read(const v8::FunctionCallbackInfo<v8::Value>& args);
void Load(const v8::FunctionCallbackInfo<v8::Value>& args);
void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
void Version(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::Handle<v8::String> ReadFile(const char* name);
void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);
在main函数中,关注如下核心代码:
{
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::Context> context = CreateShellContext(isolate);
if (context.IsEmpty()) {
fprintf(stderr, "Error creating context\n");
return 1;
}
context->Enter();
result = RunMain(isolate, argc, argv);//主函数
if (run_shell) RunShell(context);//执行shell
context->Exit();
}
v8::V8::Dispose();
核心方法关注在RunMain和RunShell
// Process remaining command line arguments and execute files
int RunMain(v8::Isolate* isolate, int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
if (strcmp(str, "--shell") == 0) { //如果是--shell,则执行shell
run_shell = true;
} else if (strcmp(str, "-f") == 0) {
// Ignore any -f flags for compatibility with the other stand-
// alone JavaScript engines.
continue;
} else if (strncmp(str, "--", 2) == 0) {
fprintf(stderr,
"Warning: unknown flag %s.\nTry --help for options\n", str);
} else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
// Execute argument given to -e option directly.
v8::Handle<v8::String> file_name = v8::String::New("unnamed");
v8::Handle<v8::String> source = v8::String::New(argv[++i]); //-e 执行字符串
if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
} else {
// Use all other arguments as names of files to load and run.
v8::Handle<v8::String> file_name = v8::String::New(str);
v8::Handle<v8::String> source = ReadFile(str); //从文件中读取javascript字符
if (source.IsEmpty()) {
fprintf(stderr, "Error reading '%s'\n", str);
continue;
}
if (!ExecuteString(isolate, source, file_name, false, true)) return 1; //执行字符串
}
}
return 0;
}
接下来看下ExecuteString
// Executes a string within the current v8 context.
bool ExecuteString(v8::Isolate* isolate,
v8::Handle<v8::String> source,
v8::Handle<v8::Value> name,
bool print_result,
bool report_exceptions) {
v8::HandleScope handle_scope(isolate);
v8::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source, name); //编译脚本
if (script.IsEmpty()) {
// Print errors that happened during compilation.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
v8::Handle<v8::Value> result = script->Run();//运行
if (result.IsEmpty()) {
assert(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
assert(!try_catch.HasCaught());
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
v8::String::Utf8Value str(result); //将结果转换为Utf8Value
const char* cstr = ToCString(str);
printf("%s\n", cstr);
}
return true;
}
}
}
接下来看看RunShell
// The read-eval-execute loop of the shell.
void RunShell(v8::Handle<v8::Context> context) {
fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
static const int kBufferSize = 256;
// Enter the execution environment before evaluating any code.
v8::Context::Scope context_scope(context);
v8::Local<v8::String> name(v8::String::New("(shell)"));
while (true) {
char buffer[kBufferSize];
fprintf(stderr, "> ");
char* str = fgets(buffer, kBufferSize, stdin);
if (str == NULL) break;
v8::HandleScope handle_scope(context->GetIsolate());
ExecuteString(context->GetIsolate(), //执行shell输入的JavaScript
v8::String::New(str),
name,
true,
true);
}
fprintf(stderr, "\n");
}
还有一个方式为ReportException
void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
v8::HandleScope handle_scope(isolate);
v8::String::Utf8Value exception(try_catch->Exception());
const char* exception_string = ToCString(exception);
v8::Handle<v8::Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
fprintf(stderr, "%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptResourceName());
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber(); //获取错误行号
fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
// Print line of source code.
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
fprintf(stderr, "%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
fprintf(stderr, " ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
fprintf(stderr, "^");
}
fprintf(stderr, "\n");
v8::String::Utf8Value stack_trace(try_catch->StackTrace()); //获取输出错误堆栈
if (stack_trace.length() > 0) {
const char* stack_trace_string = ToCString(stack_trace);
fprintf(stderr, "%s\n", stack_trace_string);
}
}
}
上面就是一个简单的shell.cc
另外一个方法创建ShellContext
v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate) {
// Create a template for the global object.
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
// Bind the global 'print' function to the C++ Print callback.
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
// Bind the global 'read' function to the C++ Read callback.
global->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read));
// Bind the global 'load' function to the C++ Load callback.
global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load));
// Bind the 'quit' function
global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit));
// Bind the 'version' function
global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version));
return v8::Context::New(isolate, NULL, global); //创建Context
}