V8是一个开源的JS和WASM引擎,用C++编写,NODE就是基于V8搞的。项目中,需要对一部分动态的规则逻辑放在体外配置和执行,并且业务的规则是需要有逻辑控制的,这里用V8是再合适不过了。目前网上找到的资料和实例,在V8版本差异下有些许不同,这里就8.2给出正确示例。
/// 执行脚本.
v8::Local<v8::Value> CompileRun(const char *js) {
v8::Local<v8::Value> result;
MaybeLocal<v8::String> source =String::NewFromUtf8(v8::Isolate::GetCurrent(), js).ToLocalChecked();
v8::TryCatch tryCatch(v8::Isolate::GetCurrent());
auto context = v8::Isolate::GetCurrent()->GetCurrentContext();
auto script = v8::Script::Compile(context, source.ToLocalChecked());
script.ToLocalChecked()->Run(context).ToLocal(&result);
return result;
}
int main(int argc, char *argv[]) {
/// 要执行的脚本.
const char *Script="JSON.stringify({'a':1});";
/// 返回的json字符串.
string resultStr;
/// 初始化V8.
v8::V8::InitializeICUDefaultLocation("");
v8::V8::InitializeExternalStartupData("");
platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate *isolate = v8::Isolate::New(create_params);
{
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
{
v8::Context::Scope context_scope(context);
v8::Local<v8::Value> result = CompileRun(Script);
if (!result.IsEmpty()) {
v8::String::Utf8Value utf8(isolate, result);
resultStr = string(*utf8);
}
}
}
printf("ret: %s\n", resultStr.data());
isolate->Dispose();
delete create_params.array_buffer_allocator;
}