Trying to compile following rust code to wasm to make it compatible running with existing js. Trying to return hashmaped value from function.
lib.rs
use wasm_bindgen::prelude::*;
use std::collections::HashMap;
#[wasm_bindgen]
pub fn get_transformed_filters()-> HashMap<i32, i32> {
let mut hm = HashMap::new();
for i in 1..9990000 {
hm.insert(i + i, i * i);
}
return hm
}
Console error after running command wasm-pack build
[INFO]: 🎯 Checking for the Wasm target...
[INFO]: 🌀 Compiling to Wasm...
Compiling hello-wasm v0.1.0 (/Users/mfe/ui/rustService/test-wasm)
error[E0277]: the trait bound `HashMap<i32, i32>: IntoWasmAbi` is not satisfied
--> src/lib.rs:15:1
|
15 | #[wasm_bindgen]
| ^^^^^^^^^^^^^^^ the trait `IntoWasmAbi` is not implemented for `HashMap<i32, i32>`
|
= note: required because of the requirements on the impl of `ReturnWasmAbi` for `HashMap<i32, i32>`
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `test-wasm`
To learn more, run the command again with --verbose.
Error: Compiling your crate to WebAssembly failed
Caused by: failed to execute `cargo build`: exited with exit code: 101
full command: "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown"
Is there any way to achieve this ?
Related
I'm newbie in Rust, and trying to compile Rust code into WASM:
use libloading::{Library, Symbol};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn main() {
// Load the DLL
let lib = unsafe { Library::new("file.dll").unwrap() };
let connect: Symbol<unsafe extern "C" fn(*const std::os::raw::c_char, *const std::os::raw::c_char) -> i32;> =
unsafe { lib.get(b"Function\0").unwrap() };
But when i run wasm-pack i'm getting the error:
error[E0432]: unresolved imports 'libloading::Library', 'libloading::Symbol'
--> src\lib.rs:1:18
|
1 | use libloading::{Library, Symbol};
| ^^^^^^^ ^^^^^^ no 'Symbol' in the root
| |
| no 'Library' in the root
For more information about this error, try 'rustc --explain E0432'`.
error: could not compile 'rust' due to previous error
Error: Compiling your crate to WebAssembly failed
Caused by: failed to execute 'cargo build': exited with exit code: 101
full command: "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown"`
If my undestanding is right - libloading can'not complie to WASM.
Does any one know way to comple such Rust code into WASM? Or may be there is any other approach to access functions from dll file in JS (React).
I'm trying:
change 'release' in toml file;
compile in binary file;
I have set up a rust base project according to the Getting Started page of the rocket-framework:
I added this line to my Cargo.toml: rocket = "0.4.10"
My main.rs:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
fn main() {
rocket::ignite().mount("/", routes![index]).launch();
}
When I try to run (or cargo build it) I get the following error:
Compiling rocket v0.4.10 error[E0277]: the trait bound `(dyn handler::Handler + 'static): handler::Handler` is not satisfied --> /Users/.../.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.10/src/rocket.rs:299:41
| 299 | let outcome = route.handler.handle(request, data);
| ^^^^^^ the trait `handler::Handler` is not implemented for `(dyn handler::Handler + 'static)`
For more information about this error, try `rustc --explain E0277`. error: could not compile `rocket` due to previous error
I also tried it with previous versions of the rocket framework, all of them threw the same error.
Of course I'm using the latest nightly version of rust, right before cargo build I entered following commands:
rustup override set nightly
info: using existing install for 'nightly-x86_64-apple-darwin'
info: override toolchain for '/Users/...' set to 'nightly-x86_64-apple-darwin'
nightly-x86_64-apple-darwin unchanged - rustc 1.58.0-nightly (bd41e09da 2021-10-18)
Is there a known issue with the latest rust compiler on MacOS? Is there any other solution I could try?
Here is the function lies in huangjj27:env_logger/src/writer/wasm.rs
//! logging functions from wasm-bindgen.
//!
//! Here use the one-param logging functions, all messages should be transformed
//! to string before passing to the functions. Note that we only need this
//! module for `wasm32-unknown-unknown` target
#![cfg(all(target_arch = "wasm32", target_vendor = "unknown"))]
// use log::Level;
use wasm_bindgen::prelude::*;
use crate::fmt::glob::Target;
pub(in crate::fmt::writer) fn print(msg: &str, t: Target) {
// work around for unused variable
let _ = t;
log(&msg);
}
As is shown above, the wasm module will only compile with wasm32-unknown-unknown target. And the print function is used in huangjj27:env_loggersrc\fmt\writer\termcolor\shim_impl.rs:
// huangjj27:env_loggersrc\fmt\writer\termcolor\shim_impl.rs: 32-48
pub(in crate::fmt::writer) fn print(&self, buf: &Buffer) -> io::Result<()> {
// This impl uses the `eprint` and `print` macros
// instead of using the streams directly.
// This is so their output can be captured by `cargo test`
let log = String::from_utf8_lossy(&buf.0);
#[cfg(all(target_arch = "wasm32", target_vendor = "unknown"))]
wasm::print(&log, self.target);
#[cfg(not(all(target_arch = "wasm32", target_vendor = "unknown")))]
match self.target {
Target::Stderr => eprint!("{}", log),
Target::Stdout => print!("{}", log),
}
Ok(())
}
then I test it with the node:
wasm-pack test --node -- --no-default-features --test node
then I get this confusing denied unused issue:
[INFO]: Checking for the Wasm target...
Compiling env_logger v0.8.2 (C:\Users\huangjj27\Documents\codes\env_logger)
error: function is never used: `print`
--> src\fmt\writer\wasm.rs:13:31
|
13 | pub(in crate::fmt::writer) fn print(msg: &str, t: Target) {
| ^^^^^
|
note: lint level defined here
--> src\lib.rs:280:54
|
280 | #![deny(missing_debug_implementations, missing_docs, warnings)]
| ^^^^^^^^
= note: `#[deny(dead_code)]` implied by `#[deny(warnings)]`
error: function is never used: `print`
--> src\fmt\writer\wasm.rs:13:31
|
13 | pub(in crate::fmt::writer) fn print(msg: &str, t: Target) {
| ^^^^^
|
note: lint level defined here
--> src\lib.rs:280:54
|
280 | #![deny(missing_debug_implementations, missing_docs, warnings)]
| ^^^^^^^^
= note: `#[deny(dead_code)]` implied by `#[deny(warnings)]`
error: aborting due to previous error
error: could not compile `env_logger`.
warning: build failed, waiting for other jobs to finish...
error: aborting due to previous error
error: could not compile `env_logger`.
To learn more, run the command again with --verbose.
Error: Compilation of your program failed
Caused by: failed to execute `cargo build`: exited with exit code: 101
full command: "cargo" "build" "--tests" "--target" "wasm32-unknown-unknown"
My questions are:
Why does the warning come out, while I indeed use the function wasm::print somewhere?
How could I deal with this problem? Working around or fixing it is ok (but I still need to keep the lint config enabled).
If you only use a function in other unused functions, then it will still give you the warning. If you want to disable the warning on that one function, you can do that by putting #[allow(dead_code)] on the line before the function header.
Here is a simple testcase, which still works on the playpen:
use std::num;
use std::str::FromStr;
use std::convert::From;
#[derive(Debug)]
struct Error(String);
impl From<num::ParseFloatError> for Error {
fn from(err: num::ParseFloatError) -> Error {
Error(format!("{}", err))
}
}
fn parse(s: &String) -> Result<f64, Error> {
Ok(try!(<f64 as FromStr>::from_str(&s[..])))
}
fn main() {
println!("{:?}", parse(&"10.01".to_string()));
}
However, after I built the latest rustc from git (now it's rustc 1.1.0-dev (1114fcd94 2015-04-23)), it stopped compiling with following error:
<std macros>:6:1: 6:32 error: the trait `core::convert::From<core::num::ParseFloatError>` is not implemented for the type `Error` [E0277]
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 6:48 note: in expansion of try!
exp.rs:15:8: 15:48 note: expansion site
error: aborting due to previous error
I'm unable to find out what's wrong. Why is the compiler unable to find my trait implementation?
This looks like it is a bug: std::num::ParseFloatError and <f64 as FromStr>::Err are different types:
the impl of FromStr for f64 is in core, and hence uses a ParseFloatError type defined in that crate, so any uses of FromStr/.parse() will get this type.
std::num defines a new ParseFloatError type, so an import from std::num gets this one.
The impl From<num::ParseFloatError> for Error is using the latter, while <f64 as FromStr>::from_str(...) is returning the former.
I opened #24748 about it. I also opened #24747 about improving the diagnostics to make this easier to debug in future.
One can work around this by insteading implementing the trait for core::num::ParseFloatError. You'll need to load the core crate with extern crate core; and will need some feature gates.
I'm trying to compile the following code, from the Rust book at the Rust official website.
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
fn main() {
let s = "Hello".to_string();
takes_slice(&s);
}
At compilation, it throws the following error
/devl/rust/bc_09/src/main.rs:7:17: 7:19 error: mismatched types:
expected &str, found &collections::string::String (expected str,
found struct collections::string::String)
/devl/rust/bc_09/src/main.rs:7 takes_slice(&s);
^~ error: aborting due to previous error Could not compile hello_world.
Here is the Rust version I'm running: rustc 1.0.0-nightly (44a287e6e 2015-01-08 17:03:40 -0800)
That's a really old version of the nightly in Rust terms! Old enough that the &String -> &str coercion isn't available. You just need to upgrade to a newer version.