1 个不稳定版本

0.0.1 2021年11月22日

#5#js-value

MIT 许可证

2.5MB
82K SLoC

C 73K SLoC // 0.0% comments JavaScript 7.5K SLoC // 0.0% comments Rust 676 SLoC // 0.0% comments Bitbake 473 SLoC // 0.1% comments Shell 104 SLoC // 0.1% comments

(WIP) rusty_qjs

Rust对QuickJS的绑定。

特性

本地

QuickJS的JSValue使用引用计数来管理内存。因此,我们创建了一个Local处理程序来帮助您管理引用计数。Local实现Clone使用JS_DupValue来增加引用计数,并实现Drop使用JS_FreeValue来减少引用计数。您可以使用to_local将JSValue转换为Local处理程序,然后享受它的便利。

示例

use rusty_qjs::{CallContext, JSContext, JSRuntime, JSValue};
use std::io::Write;

extern "C" fn js_print(
  ctx: *mut JSContext,
  this_val: JSValue,
  argc: i32,
  argv: *mut JSValue,
) -> JSValue {
  let mut ctx = unsafe { ctx.as_mut() }.unwrap();
  let mut call_ctx = CallContext::new(&mut ctx, this_val, argc, argv);

  let mut stdout = std::io::stdout();
  for i in 0..call_ctx.argc {
    if i != 0 {
      stdout.write_all(b" ").unwrap();
    }
    let val = call_ctx.get(i).unwrap();
    stdout
      .write_all(val.to_string(call_ctx.js_context).as_bytes())
      .unwrap();
  }
  stdout.write_all(b"\n").unwrap();
  JSValue::new_undefined()
}

fn setup_console(ctx: &mut JSContext) {
  let global = ctx.get_global_object().to_local(ctx);
  let console = JSValue::new_object(ctx).to_local(ctx);
  let log = JSValue::new_function(ctx, js_print, "log", 1).to_local(ctx);

  console.set_property_str("log", log).unwrap();
  global.set_property_str("console", console).unwrap();
}

fn main() {
  let rt = &mut JSRuntime::new();
  let ctx = &mut JSContext::new(rt);

  setup_console(ctx);
  ctx.eval_script("console.log(\"hello world\")", "<test>");
}

依赖项