最简单和最符合习惯的解决方案
大多数人应该使用wasm-bindgen,这使得整个过程变得简单得多!
低级手动实现
要在JavaScript和Rust之间传输字符串数据,您需要决定:
- 文本的编码方式:UTF-8(Rust本地)还是UTF-16(JS本地)。
- 谁将拥有内存缓冲区:JS(调用方)还是Rust(被调用方)。
- 如何表示字符串数据和长度:以NUL结尾(C风格)或不同长度(Rust风格)。
- 如果它们是分开的,如何通信数据和长度。
常见设置
构建WASM的C dylibs非常重要,可以帮助它们更小。
Cargo.toml
[package]
name = "quick-maths"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
[lib]
crate-type = ["cdylib"]
.cargo/config
[target.wasm32-unknown-unknown]
rustflags = [
"-C", "link-args=--import-memory",
]
package.json
{
"name": "quick-maths",
"version": "0.1.0",
"main": "index.js",
"author": "An Devloper <an.devloper@example.com>",
"license": "MIT",
"scripts": {
"example": "node ./index.js"
},
"dependencies": {
"fs-extra": "^8.0.1",
"text-encoding": "^0.7.0"
}
}
我正在使用NodeJS 12.1.0。
执行
$ rustup component add rust-std --target wasm32-unknown-unknown
$ cargo build --release --target wasm32-unknown-unknown
解决方案 1
我的决定是:
- 将 JS 字符串转换为 UTF-8,这意味着
TextEncoder
JS API 是最合适的。
- 调用者应拥有内存缓冲区。
- 长度应该是一个单独的值。
- 另一个结构体和分配应该用来保存指针和长度。
lib/src.rs
#[repr(C)]
pub struct JsInteropString {
data: *const u8,
len: usize,
}
#[no_mangle]
pub unsafe extern "C" fn compute(s: *const JsInteropString, n1: i32, n2: i32) -> i32 {
let s = match s.as_ref() {
Some(s) => s,
None => return -1,
};
let data = std::slice::from_raw_parts(s.data, s.len);
match std::str::from_utf8(data) {
Ok(s) => real_code::compute(s, n1, n2),
Err(_) => -2,
}
}
mod real_code {
pub fn compute(operator: &str, n1: i32, n2: i32) -> i32 {
match operator {
"SUM" => n1 + n2,
"DIFF" => n1 - n2,
"MULT" => n1 * n2,
"DIV" => n1 / n2,
_ => 0,
}
}
}
index.js
const fs = require('fs-extra');
const { TextEncoder } = require('text-encoding');
const memory = new WebAssembly.Memory({ initial: 20, maximum: 100 });
const importObject = {
env: { memory }
};
const memoryManager = (memory) => {
var base = 0;
base += 4;
return {
encodeString: (jsString) => {
const encoder = new TextEncoder();
const encodedString = encoder.encode(jsString);
const asU32 = new Uint32Array(memory.buffer, base, 2);
const asBytes = new Uint8Array(memory.buffer, asU32.byteOffset + asU32.byteLength, encodedString.length);
asBytes.set(encodedString);
asU32[0] = asBytes.byteOffset;
asU32[1] = asBytes.length;
const originalBase = base;
base += asBytes.byteOffset + asBytes.byteLength;
return originalBase;
}
};
};
const myMemory = memoryManager(memory);
fs.readFile('./target/wasm32-unknown-unknown/release/quick_maths.wasm')
.then(bytes => WebAssembly.instantiate(bytes, importObject))
.then(({ instance }) => {
const argString = "MULT";
const argN1 = 42;
const argN2 = 100;
const s = myMemory.encodeString(argString);
const result = instance.exports.compute(s, argN1, argN2);
console.log(result);
});
执行
$ yarn run example
4200
解决方案2
我决定:
- 将JS字符串转换为UTF-8,这意味着
TextEncoder
JS API最适合。
- 模块应拥有内存缓冲区。
- 长度应该是一个单独的值。
- 使用
Box<String>
作为底层数据结构。这允许分配进一步被Rust代码使用。
src/lib.rs
#[repr(transparent)]
pub struct JsInteropString(*mut String);
impl JsInteropString {
unsafe fn with_capacity(cap: usize) -> Self {
let mut d = Vec::with_capacity(cap);
d.set_len(cap);
let s = Box::new(String::from_utf8_unchecked(d));
JsInteropString(Box::into_raw(s))
}
unsafe fn as_string(&self) -> &String {
&*self.0
}
unsafe fn as_mut_string(&mut self) -> &mut String {
&mut *self.0
}
unsafe fn into_boxed_string(self) -> Box<String> {
Box::from_raw(self.0)
}
unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
self.as_mut_string().as_mut_vec().as_mut_ptr()
}
}
#[no_mangle]
pub unsafe extern "C" fn stringPrepare(cap: usize) -> JsInteropString {
JsInteropString::with_capacity(cap)
}
#[no_mangle]
pub unsafe extern "C" fn stringData(mut s: JsInteropString) -> *mut u8 {
s.as_mut_ptr()
}
#[no_mangle]
pub unsafe extern "C" fn stringLen(s: JsInteropString) -> usize {
s.as_string().len()
}
#[no_mangle]
pub unsafe extern "C" fn compute(s: JsInteropString, n1: i32, n2: i32) -> i32 {
let s = s.into_boxed_string();
real_code::compute(&s, n1, n2)
}
mod real_code {
pub fn compute(operator: &str, n1: i32, n2: i32) -> i32 {
match operator {
"SUM" => n1 + n2,
"DIFF" => n1 - n2,
"MULT" => n1 * n2,
"DIV" => n1 / n2,
_ => 0,
}
}
}
index.js
const fs = require('fs-extra');
const { TextEncoder } = require('text-encoding');
class QuickMaths {
constructor(instance) {
this.instance = instance;
}
difference(n1, n2) {
const { compute } = this.instance.exports;
const op = this.copyJsStringToRust("DIFF");
return compute(op, n1, n2);
}
copyJsStringToRust(jsString) {
const { memory, stringPrepare, stringData, stringLen } = this.instance.exports;
const encoder = new TextEncoder();
const encodedString = encoder.encode(jsString);
const rustString = stringPrepare(encodedString.length);
const rustStringData = stringData(rustString);
const asBytes = new Uint8Array(memory.buffer, rustStringData, encodedString.length);
asBytes.set(encodedString);
return rustString;
}
}
async function main() {
const bytes = await fs.readFile('./target/wasm32-unknown-unknown/release/quick_maths.wasm');
const { instance } = await WebAssembly.instantiate(bytes);
const maffs = new QuickMaths(instance);
console.log(maffs.difference(100, 201));
}
main();
执行
$ yarn run example
-101
注意,这个过程可以用于其他类型。你只需要决定如何将数据表示为双方都同意的一组字节,然后发送它即可。
另请参阅:
&str
)。请查看我的 Rust FFI Omnibus。虽然它目前还没有针对 WebAssembly 的内容,但其中的概念仍然是有效的。 - Shepmaster