从 rust wasm32-wasi 调用 console.log 而不需要 ssvm/ssvmup

问题描述

我想使用到 console.log 的消息进行调试。

我们有一个 rust wasm32-wasi 函数被在 nodejs 中运行的 javascript 调用。由于其他限制,我们无法使用 ssvm/ssvmup。

我们可以做些什么来在控制台中查看来自我们 wasm 代码的消息吗?

解决方法

这在 The wasm-bindgen Guide: Using console.log 中得到了回答:

  • 方法#1,手动绑定:

    #[wasm_bindgen]
    extern "C" {
        // Use `js_namespace` here to bind `console.log(..)` instead of just
        // `log(..)`
        #[wasm_bindgen(js_namespace = console)]
        fn log(s: &str);
    
        // The `console.log` is quite polymorphic,so we can bind it with multiple
        // signatures. Note that we need to use `js_name` to ensure we always call
        // `log` in JS.
        #[wasm_bindgen(js_namespace = console,js_name = log)]
        fn log_u32(a: u32);
    
        // Multiple arguments too!
        #[wasm_bindgen(js_namespace = console,js_name = log)]
        fn log_many(a: &str,b: &str);
    }
    
    fn bare_bones() {
        log("Hello from Rust!");
        log_u32(42);
        log_many("Logging","many values!");
    }
    
  • 方法 #2,使用 web-sys 板条箱:

    fn using_web_sys() {
        use web_sys::console;
    
        console::log_1(&"Hello using web-sys".into());
    
        let js: JsValue = 4.into();
        console::log_2(&"Logging arbitrary values looks like".into(),&js);
    }
    

另一种可能的替代方案,如果您要进行大量日志记录,您可能需要考虑使用 log 板条箱和 wasm-logger 门面:

wasm_logger::init(wasm_logger::Config::default());

// Logging
log::info!("Some info");
log::error!("Error message");

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...