【问题标题】:Calling console.log from rust wasm32-wasi without the need for ssvm/ssvmup从 rust wasm32-wasi 调用 console.log 而不需要 ssvm/ssvmup
【发布时间】:2021-03-27 21:53:23
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否使用wasm-bindgenneon 之类的方式进行集成?
  • @kmdreko 使用 wasm-bindgen

标签: node.js rust wasi


【解决方案1】:

The wasm-bindgen Guide: Using console.log:

  • 方法一,手动绑定:

    #[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 crate:

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

另一种可能的替代方法,如果您要进行大量日志记录,您可能需要考虑使用带有 wasm-logger 外观的 log 板条箱:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多