我从这个Rust代码创建了一个小的WASM文件:
#[no_mangle]
pub fn hello() -> &'static str {
"hello from rust"
}
Run Code Online (Sandbox Code Playgroud)
它构建并且hello可以从JS调用该函数:
<!DOCTYPE html>
<html>
<body>
<script>
fetch('main.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(results => {
alert(results.instance.exports.hello());
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的问题是alert显示"未定义".如果我返回a i32,它可以工作并显示i32.我也尝试返回String但是它不起作用(它仍然显示"未定义").
有没有办法从WebAssembly中的Rust返回一个字符串?我应该使用什么类型的?