【发布时间】:2018-06-08 09:37:48
【问题描述】:
我正在为 Rust 尝试新的 wasm32-unknown-unknown 目标,但在调用数学函数(例如 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>
我用命令构建项目
cargo build --release --target wasm32-unknown-unknown
当我在 Firefox 中打开 html 文件时,出现以下错误:
LinkError: import object field 'sin' is not a Function
我的设置有问题吗?或者这是 Rust/WebAssembly/Firefox 中的一个缺点?我可以手动将 sin 函数添加到 javascript 中的 imports.env 对象中,但这看起来很笨拙,我必须对我使用的每个数学函数都这样做。有没有更好的办法?
我正在使用 nightly Rust 工具链(nightly-x86_64-unknown-linux-gnu rustc 1.24.0-nightly (cddc4a62d 2017-12-26))和 Firefox 57.0.1(64 位)。
【问题讨论】:
标签: rust webassembly