I'm trying the new wasm32-unknown-unknown target for Rust, and I'm experiencing issues invoking math functions (e.g. sin, cos, exp, atan2).
Cargo.toml:
[package]
name = "wasm_math"
version = "0.1.0"
authors = ["..."]
[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]
[dependencies]
src/lib.rs:
#[no_mangle]
pub extern "C" fn invoke_sin(x: f64) -> f64 {
x.sin()
}
index.html:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Wasm Math</title></head>
<body></body>
<script>
const imports = { env: { } };
fetch("target/wasm32-unknown-unknown/release/wasm_math.wasm").then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, imports)
).then(results => {
alert(results.instance.exports.invoke_sin(1.0));
});
</script>
</html>
I build the project with the command
cargo build --release --target wasm32-unknown-unknown
When I open the html file in firefox, I get the following error:
LinkError: import object field 'sin' is not a Function
Is there something wrong with my setup? Or is this a shortcoming in Rust/WebAssembly/Firefox? I could manually add the sin
function to the imports.env
object in the javascript, but that seems very hacky and I would have to do that for every math function that I use. Is there a better way?
I'm using the nightly Rust toolchain (nightly-x86_64-unknown-linux-gnu rustc 1.24.0-nightly (cddc4a62d 2017-12-26)) and Firefox 57.0.1 (64-bit).