您的位置:首页 > Web前端 > JavaScript

Javascript V8 引擎

2017-02-23 18:42 507 查看
1、暴露C++函数接口供js脚本调用:

流程如下:

 个人的理解如下(不确定是否理解有误)  Isolate 代表一个 运行实例 ,类似于虚拟机 , 同一时刻只能被一个线程运行,  从 isolate实例获取到全局的对象模板, 然后把 需要 给js调用的接口注册进去, 那么在这一个实例中 运行的上下文环境 就可以识别到这个C++拓展接口。

  假设有如下C++接口

void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
bool first = true;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(args[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
const char* s_result = "print call succeed\n";
v8::Local<v8::String>  v_result = v8::String::NewFromUtf8(args.GetIsolate(), s_result,
v8::NewStringType::kNormal).ToLocalChecked();
args.GetReturnValue().Set(v_result);
}
printf("\n");
fflush(stdout);
}
生成 Isolate *isolate实例之后, 获取 上下文执行环境 context 之前

v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
// Bind the global 'print' function to the C++ Print callback.
global->Set(
v8::String::NewFromUtf8(isolate, "print", v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::FunctionTemplate::New(isolate, Print));


获取上下文 
Local<Context> context = v8::Context::New(isolate, NULL, global);
完成之后 在javsscript中调用  print 函数的时候 将会调用C++ 接口的 Print
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: