如何从Tinygo WebAssembly目标返回对象

发布于 2025-02-05 14:20:56 字数 887 浏览 1 评论 0原文

我正在使用tinygo生成一个用于简单函数的WASM:

//export onInput
func onInput() map[string]interface{} {
    return map[string]interface{}{
        "key": 60,
        "remove": 1,
    }
}

然后,我使用WASM Target使用TinyGo来构建AS:

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功能中返回的数组,字符串或地图。我会为上述任何一个安顿下来。

I am using tinygo to generate a wasm for simple function:

//export onInput
func onInput() map[string]interface{} {
    return map[string]interface{}{
        "key": 60,
        "remove": 1,
    }
}

Then I am using wasm target to build using tinygo, as:

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

And when I call the method wasm.exports.onInput() I am getting a number such as: 102752

How would I get the JS object as a return value like:

{ key: 60, remove: 1 }

// Or array [60, 1] if possible

Note:

The tinygo documentation says:

The WebAssembly target does not return variables directly that cannot be handled by JavaScript (see above about i64, also struct, i64, multiple return values, etc). Instead, they are stored into a pointer passed as the first parameter by the caller.

If that's the cause of the issue, how would I pass the return value as a pointer from javascript?

Edit

I wasn’t able to figure out how I would return any of: arrays, strings or maps from a go function. I would settle for any of the above.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野の 2025-02-12 14:20:56

根据

package main

import "syscall/js"

func main() {
    wait := make(chan struct{}, 0)
    js.Global().Set("onInput", js.FuncOf(onInput))
    <-wait
}

// note that there is no export as we registered this function in global
func onInput(this js.Value, args []js.Value) interface{} {
    return js.ValueOf(map[string]interface{}{
        "key":    60,
        "remove": 1,
    })
}

在您的JS代码中,仅使用oninput,没有ismmmodule.Instance.Exports.exports prefix

According to example at tinygo github you can try something like this:

package main

import "syscall/js"

func main() {
    wait := make(chan struct{}, 0)
    js.Global().Set("onInput", js.FuncOf(onInput))
    <-wait
}

// note that there is no export as we registered this function in global
func onInput(this js.Value, args []js.Value) interface{} {
    return js.ValueOf(map[string]interface{}{
        "key":    60,
        "remove": 1,
    })
}

And in your js code use just onInput, without wasmModule.instance.exports prefix

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文