我尝试将此Rust代码编译为WebAssembly:
#[no_mangle]
pub fn rust_function() -> String {
let mut a = vec![];
for x in 0..100 {
a.push(x);
}
return a.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join("-");
}
当我在NodeJS中使用WebAssembly执行它时,它会给出一个未定义的结果:
const fs = require('fs');
const buf = fs.readFileSync('target/wasm32-unknown-unknown/release/hello_world.wasm');
function toUint8Array(buf) {
var u = new Uint8Array(buf.length)
for (var i = 0; i < buf.length; ++i) {
u[i] = buf[i]
}
return u
}
const arrayBuffer = toUint8Array(buf);
const result = WebAssembly.instantiate(arrayBuffer);
result.then((res)=>{
console.log(res.instance.exports.rust_function());
})
它适用于其他目标。