gpt4 book ai didi

Rust wasm32-unknown-unknown 数学函数不链接

转载 作者:行者123 更新时间:2023-11-29 07:57:32 31 4
gpt4 key购买 nike

我正在尝试 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]

源/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 位)。

最佳答案

根据WASM FAQ sin 不包括在内。

•WebAssembly doesn’t include its own math functions like sin , cos , exp , pow , and so on. WebAssembly’s strategy for such functions is to allow them to be implemented as library routines in WebAssembly itself (note that x86’s sin and cos instructions are slow and imprecise and are generally avoided these days anyway). Users wishing to use faster and less precise math functions on WebAssembly can simply select a math library implementation which does so.

Rust 似乎依赖 LLVM 来提供 sin ( f64 impl here ),而 WASM 则没有。我认为 LLVM 应该 将其作为其 llvm.sin.f64 内在的一部分提供,但似乎他们不保证每个目标的实现 https://llvm.org/docs/LangRef.html#llvm-sin-intrinsic (强调我的):

This is an overloaded intrinsic. You can use llvm.sin on any floating-point or vector of floating-point type. Not all targets support all types however.

或许,鉴于此,Rust 应该考虑自己实现 sin

关于Rust wasm32-unknown-unknown 数学函数不链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997306/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com