mar*_*ina 4 rust rust-cargo webassembly wasm-bindgen wasm-pack
我正在构建一个 Chrome 扩展程序,并选择使用一些 WebAssembly 功能。我使用 wasm-pack 来构建源代码,因为它提供了--target web降低插入 Wasm 函数的复杂性的方法。在 Rust 和 JS 之间传递整数值可以无缝地工作,但我似乎无法将字符串传递给 Rust,反之亦然。
这是我正在处理的内容:
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
#[wasm_bindgen(js_namespace = console)]
fn log(x: &str);
}
#[wasm_bindgen]
pub extern "C" fn add_two(x: i32) -> i32 {
x + 2
}
#[wasm_bindgen]
pub fn hello(name: &str) {
log("Hello") // <-- passing a '&str' directly works. I can see it in the browser.
log(name) // <-- does not seem to work. There is no output
alert(&format!("Hello {}", name)); // <- Only output im getting is "Hello !"
}
Run Code Online (Sandbox Code Playgroud)
更新:有关如何导入和实例化 wasm 的更多信息
使用 wasm-pack 构建并将生成的 pkg 目录导入到我的 JS 文件夹中后。我通过 manifest.json 文件将 pkg 目录的内容作为 web_resource 提供给项目使用。
这是我在 content_script.js 中加载脚本的方式
(async function() {
// Get the JS File
const src = await import("/pkg/rusty.js");
// Fetch the wasm file.
const wasm_src = chrome.extension.getURL("/pkg/rusty_bg.wasm");
//src has an exported function 'default' that initializes the WebAssembly module.
let wasm = await src.default(wasm_src);
wasm.hello("stack-overflow");
})();
Run Code Online (Sandbox Code Playgroud)
问题在于您如何加载代码:
(async function() {
// Get the JS File
const src = await import("/pkg/rusty.js");
// Fetch the wasm file.
const wasm_src = chrome.extension.getURL("/pkg/rusty_bg.wasm");
//src has an exported function 'default' that initializes the WebAssembly module.
let wasm = await src.default(wasm_src);
wasm.hello("stack-overflow");
})();
Run Code Online (Sandbox Code Playgroud)
wasm返回的.default(...)对象是具有原始 WebAssembly 导出的对象,只能对原始数字进行操作。
在这种情况下,wasm.hello需要两个整数——WebAssembly 内存中字符串的指针和长度——而 JavaScript 很乐意转换"stack-overflow"为0并提供另一个0整数作为默认值,这就是为什么你最终会在 Rust 上得到一个空字符串。边。
相反,您想要的是负责正确转换的函数的包装版本。这些直接存在于.js文件的导入中:
(async function() {
// Get the JS File
const rusty = await import("/pkg/rusty.js");
// Fetch the wasm file.
const wasm_src = chrome.extension.getURL("/pkg/rusty_bg.wasm");
// rusty has an exported function 'default' that initializes the WebAssembly module.
await rusty.default(wasm_src);
rusty.hello("stack-overflow"); // it works!
})();
Run Code Online (Sandbox Code Playgroud)