猿问

如何从 tinygo webassembly 目标返回对象

我正在使用 tinygo 为简单的功能生成一个 wasm:


//export onInput

func onInput() map[string]interface{} {

    return map[string]interface{}{

        "key": 60,

        "remove": 1,

    }

}

然后我使用 wasm 目标使用 tinygo 构建,如:


tinygo build -o main.wasm -target wasm ./main.go

当我调用该方法wasm.exports.onInput()时,我得到一个数字,例如:102752


我将如何获取 JS 对象作为返回值,例如:


{ key: 60, remove: 1 }


// Or array [60, 1] if possible

笔记:


tinygo 文档说:


WebAssembly 目标不会直接返回 JavaScript 无法处理的变量(参见上面关于 i64,还有 struct,i64,多个返回值等)。相反,它们存储在由调用者作为第一个参数传递的指针中。


如果那是问题的原因,我将如何将返回值作为来自 javascript 的指针传递?


编辑


我无法弄清楚如何从 go 函数返回数组、字符串或映射。我会满足于以上任何一种。


GCT1015
浏览 75回答 1
1回答

蝴蝶刀刀

根据tinygo github 上的示例,您可以尝试这样的操作:package mainimport "syscall/js"func main() {&nbsp; &nbsp; wait := make(chan struct{}, 0)&nbsp; &nbsp; js.Global().Set("onInput", js.FuncOf(onInput))&nbsp; &nbsp; <-wait}// note that there is no export as we registered this function in globalfunc onInput(this js.Value, args []js.Value) interface{} {&nbsp; &nbsp; return js.ValueOf(map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; "key":&nbsp; &nbsp; 60,&nbsp; &nbsp; &nbsp; &nbsp; "remove": 1,&nbsp; &nbsp; })}在你的 js 代码中使用 just onInput, without wasmModule.instance.exportsprefix
随时随地看视频慕课网APP

相关分类

Go
我要回答