Home > Enterprise >  How to return object from tinygo webassembly target
How to return object from tinygo webassembly target

Time:06-08

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.

CodePudding user response:

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

  • Related