gpt4 book ai didi

node.js - 如何使用 wasm bindgen 从 Nodejs-WebAssembly 中的 Rust 函数返回字符串?

转载 作者:行者123 更新时间:2023-12-04 14:45:53 32 4
gpt4 key购买 nike

我是 Rust 和 WASM 的新手,正在努力运行第一个程序。

[dependencies]
wasm-bindgen = { version = "0.2.63" }

我有以下编译为 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;
}
还有我的 Node 代码(灵感来自 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));
这日志
function
x undefined
我尝试了两种连接字符串的方法,或者我在返回值方面做错了什么?

最佳答案

在没有更多样板的 Node 中使用 WebInstantiate 时,就像您一样,我得到了相同的结果( undefined )。在浏览器中无缝运行的东西在 node.js 中效果不佳。
但是当我专门构建一个 Node 模块时,我得到了字符串交换

wasm-pack build --target nodejs
有了 Node 模块,使用起来也简单多了:
const wasmModule = require("./pkg/hello_world.js");
const greet = wasmModule.greet;
const greeting = greet("Simon");
console.log('greeting:', greeting);

关于node.js - 如何使用 wasm bindgen 从 Nodejs-WebAssembly 中的 Rust 函数返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70079979/

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