【问题标题】:How to Pass a String from Js to Wasm generated through Rust using Wasm-Bindgen Web_sys Wasm-pack如何使用 Wasm-Bindgen Web_sys Wasm-pack 将字符串从 Js 传递到通过 Rust 生成的 Wasm
【发布时间】:2020-09-11 04:16:01
【问题描述】:

代码是基本的,我从 js 调用一个函数,它带有一个在 lib.rs 中声明的字符串输入 但是字符串没有传递给 wasm 中的函数我收到一个空字符串,反向也不起作用我也无法将字符串从 wasm 传递给 js。

wasm 文件长这样

use wasm_bindgen::prelude::*;
use web_sys::console;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
pub fn hello(v: String) {
    console::log_1(&v.into()); //prints => empty string
}

js 看起来这个 wasm 已经成功启动,其他功能正常

wasm.hello("hello")

货物 toml 是这样的

[package]
name = "painter"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[features]
default = ["console_error_panic_hook"]

[dependencies]
wasm-bindgen = "0.2"
#web-sys = "0.3.39"

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.1", optional = true }

[dependencies.web-sys]
version = "0.3.39"
features = [
  "console",
  "Document",
  "Element",
  "HtmlElement",
  "Node",
  "Window"
 ]  # Do you have this line in your Cargo.toml?

# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
#
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = "0.4.2", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.2"

[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"

【问题讨论】:

    标签: rust webassembly wasm-bindgen wasm-pack


    【解决方案1】:

    我发现我使用的是来自 wasm init 的导出,而不是来自通过 wasm-pack 生成的 js 文件的导出,因此在使用 wasm-pack 导出时请记住这一点,并在启动后使用它js文件

    【讨论】:

    • 我犯了同样的错误。如果其他人遇到这个问题,这里有一个澄清的例子:wasmbyexample.dev/examples/… 请密切注意导入语法。如果您使用 wasm-bindgen,则不应直接在 wasm 对象上调用方法,因为这会绕过绑定代码并且会默默地失败(以经典 JS 风格)。这对我来说似乎是一个奇怪的 API 设计,但我对 JS 的理解还不够流利,无法发表评论。
    • 哇,感谢您为我节省了时间!这非常容易出错。
    猜你喜欢
    • 2021-09-15
    • 2020-02-29
    • 2020-08-29
    • 2023-01-07
    • 1970-01-01
    • 2020-06-15
    • 2020-07-13
    • 2019-07-11
    • 2021-03-22
    相关资源
    最近更新 更多