一、暴露C++函數(shù)接口供JavaScript腳本調(diào)用:##
流程如下:
Isolate代表一個(gè)運(yùn)行實(shí)例,可以理解為類似于一個(gè)虛擬機(jī),同一時(shí)刻只能被一個(gè)線程運(yùn)行,但是Isolate可以有多個(gè)。從Isolate實(shí)例獲取到全局的對象模板,然后把需要給JavaScript調(diào)用的接口注冊到isolate中, 那么在這個(gè)實(shí)例運(yùn)行上下文環(huán)境就可以識別到這個(gè)被注冊的C++拓展接口。
假設(shè)有如下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);
}
在使用V8引擎的過程中,初始化環(huán)境,生成Isolate *isolate實(shí)例之后,獲取上下文環(huán)境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));
然后從該Isolate獲取執(zhí)行環(huán)境上下文:
Local<Context> context = v8::Context::New(isolate, NULL, global);
之后在JS中調(diào)用print函數(shù)的時(shí)候,C++接口的print函數(shù)就會(huì)被調(diào)用。