跳到主要内容

V8

基础

V8 中的一些概念

GlobalValue JS 的变量

LocalValue V8 的变量

rusty_v8

使用 v8 运行 JS 代码,并为 JS 环境注入 rust 函数

rusty_v8 已经更名为 v8

依赖 v8 = "0.74" serde_v8 = "0.37"

fn print(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut _rv: v8::ReturnValue,
) {
let result = args.get(0).to_string(scope).unwrap();
println!("Rust says: {}", result.to_rust_string_lossy(scope));
}

fn main() {
// initializa v8 engine
init();

// create a new isolate
let params = v8::CreateParams::default();
let isolate = &mut v8::Isolate::new(params);

// create handle scope
let handle_scope = &mut v8::HandleScope::new(isolate);
// create context
let context = v8::Context::new(handle_scope);
// create context scope
let context_scope = &mut v8::ContextScope::new(handle_scope, context);

// 为 JS 提供 rust 函数
let bindings = v8::Object::new(context_scope);
let name = v8::String::new(context_scope, "print").unwrap();
let func = v8::Function::new(context_scope, print).unwrap();
bindings
.set(context_scope, name.into(), func.into())
.unwrap();

// js code
let glue_code = r#"
'use strict';
({print}) => {
globalThis.print = print;
};
"#;
// 运行 glue 代码,把 rust 函数绑定到 JS
let glue_code = v8::String::new(context_scope, glue_code).unwrap();
let script = v8::Script::compile(context_scope, glue_code, None).unwrap();
if let Some(result) = script.run(context_scope) {
let func = v8::Local::<v8::Function>::try_from(result).unwrap();
let v = v8::undefined(context_scope).into();
let args = [bindings.into()];
func.call(context_scope, v, &args).unwrap();
}

// js code
let source = r#"
print('Hello World!');
"#;
let source = v8::String::new(context_scope, source).unwrap();
let script = v8::Script::compile(context_scope, source, None).unwrap();
script.run(context_scope).unwrap();
}

fn init() {
let platform = v8::new_default_platform(0, false).make_shared();
v8::V8::initialize_platform(platform);
v8::V8::initialize();
}

rust