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