43个版本
0.2.93 | 2024年8月12日 |
---|---|
0.2.92 | 2024年3月4日 |
0.2.91 | 2024年2月6日 |
0.2.89 | 2023年11月27日 |
0.2.55 | 2019年11月19日 |
在WebAssembly中排名1475
每月下载量174,073
在34个crate中使用(通过wasm-bindgen-cli-support)
24KB
380 代码行
wasm-bindgen
多值转换。
这个crate提供了一种转换,将使用返回指针的导出函数转换为使用多值的导出函数。
考虑以下函数
#[no_mangle]
pub extern "C" fn pair(a: u32, b: u32) -> [u32; 2] {
[a, b]
}
LLVM默认会将此编译成以下Wasm
(func $pair (param i32 i32 i32)
local.get 0
local.get 2
i32.store offset=4
local.get 0
local.get 1
i32.store)
这里发生的事情是函数并没有直接返回这对值,而是第一个i32
参数是指向一些临时空间的指针,返回值写入该临时空间。LLVM这样做是因为它还没有支持多值Wasm,因此它只能一次返回一个值。
理想情况下,使用多值,我们希望得到的是这个
(func $pair (param i32 i32) (result i32 i32)
local.get 0
local.get 1)
然而,这个转换目前并不是这样做的。这个转换比修改现有函数以产生多值结果要简单一些,它引入了新的函数,这些函数封装了原始函数,并将返回指针转换为多值结果。
在我们的运行示例中,我们得到这个
;; The original function.
(func $pair (param i32 i32 i32)
local.get 0
local.get 2
i32.store offset=4
local.get 0
local.get 1
i32.store)
(func $pairWrapper (param i32 i32) (result i32 i32)
;; Our return pointer that points to the scratch space we are allocating
;; on the stack for calling `$pair`.
(local i32)
;; Allocate space on the stack for the result.
global.get $stackPointer
i32.const 8
i32.sub
local.tee 2
global.set $stackPointer
;; Call `$pair` with our allocated stack space for its results.
local.get 2
local.get 0
local.get 1
call $pair
;; Copy the return values from the stack to the wasm stack.
local.get 2
i32.load
local.get 2 offset=4
i32.load
;; Finally, restore the stack pointer.
local.get 2
i32.const 8
i32.add
global.set $stackPointer)
这个$pairWrapper
函数是我们实际导出的,而不是$pair
。
依赖关系
~6.5MB
~140K SLoC