C++ V8 8.2的使用

编程入门 行业动态 更新时间:2024-10-27 12:27:27

C++ V8 8.2的使用

C++ V8 8.2的使用

       ​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;
}

更多推荐

C++ V8 8.2的使用

本文发布于:2024-02-12 18:06:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1688841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!