How to Pass a String from Js to Wasm generated through Rust using Wasm-Bindgen Web_sys Wasm-pack

Viewed 599

the code is basic i am calling a function from js with a string input which is declared in the lib.rs but the string is not passing onto the function in wasm i am receiving an empty string and the reverse is also not working i am not able to pass a string from wasm to js either.

wasm file looks like this

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 looks like this wasm is already initiated successfully other functions are working fine

wasm.hello("hello")

cargo toml looks like this

[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"

1 Answers

well i figured it out i was using the exports from wasm init not from the exports of the js file that was generated via wasm-pack so keep that in mind while using wasm-pack exports and also use it after you initiate the js file

Related