[英]How do I return a string from a Rust function in Nodejs-WebAssembly using wasm bindgen?
I'm new to Rust and WASM and struggling to get a first program running.我是 Rust 和 WASM 的新手,正在努力让第一个程序运行。
[dependencies]
wasm-bindgen = { version = "0.2.63" }
I have the following Rust that compiles to WASM我有以下编译为 WASM 的 Rust
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
// let val = ["Hello", name].join(" ");
let val = format!("Hello {}", name);
return val;
}
And my node code (inspired by https://nodejs.dev/learn/nodejs-with-webassembly ),还有我的节点代码(受https://nodejs.dev/learn/nodejs-with-webassembly启发),
const fs = require("fs");
const wasmBuffer = fs.readFileSync("../pkg/hello_world_bg.wasm");
WebAssembly.instantiate(wasmBuffer)
.then((wasmModule) => {
// Exported function live under instance.exports
const greet = wasmModule.instance.exports.greet;
console.log(typeof greet);
const greeting = greet("Simon");
console.log("x", greeting);
})
.catch((err) => console.log(err));
This logs这记录
function
x undefined
I tried two ways of concatenating the strings, or perhaps I am doing something wrong with the return value?我尝试了两种连接字符串的方法,或者我对返回值做错了什么?
When using WebInstantiate in node without more boilerplate, just like you did, I got the same result ( undefined
).在没有更多样板的节点中使用 WebInstantiate 时,就像您所做的那样,我得到了相同的结果(
undefined
)。 What works seamlessly in the browser doesn't work so well in node.在浏览器中无缝运行的东西在节点中运行得不太好。
But I got string exchange working when specifically building a node module with但是当我专门构建一个节点模块时,我得到了字符串交换
wasm-pack build --target nodejs
With a node module, usage is also much simpler:使用节点模块,使用也简单得多:
const wasmModule = require("./pkg/hello_world.js");
const greet = wasmModule.greet;
const greeting = greet("Simon");
console.log('greeting:', greeting);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.