首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Wasm-Bindgen Web_sys Wasm-pack将字符串从Js传递到Wasm

如何使用Wasm-Bindgen Web_sys Wasm-pack将字符串从Js传递到Wasm
EN

Stack Overflow用户
提问于 2020-05-24 21:52:08
回答 1查看 284关注 0票数 2

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

wasm文件如下所示

代码语言:javascript
复制
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已经成功初始化了,其他函数运行正常。

代码语言:javascript
复制
wasm.hello("hello")

cargo toml看起来像这样

代码语言:javascript
复制
[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"
EN

回答 1

Stack Overflow用户

发布于 2020-05-24 22:15:54

我已经弄清楚了,我使用的是wasm init的导出,而不是通过wasm-pack生成的js文件的导出,所以在使用wasm-pack导出时请记住这一点,并在启动js文件之后使用它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61986932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档