是否可以从JS显式调用导出的Go WebAssembly函数? [英] Is it possible to explicitly call an exported Go WebAssembly function from JS?

查看:61
本文介绍了是否可以从JS显式调用导出的Go WebAssembly函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Javascript中调用除 main 之外的Go WebAssembly函数?

Is it possible to call a Go WebAssembly function, other than main, in Javascript?

首先让我展示一下我做了什么.我的Go函数定义如下:

Let me first show what I did. My Go functions are defined as follows:

package main

import "fmt"

func main() {
    fmt.Println("it works!")
}

func add(a, b int) int {
    return a + b
}

我只能调用 main 函数:

const go = new Go();

const data   = await fetch("http://localhost:3333/main.wasm");
const result = await WebAssembly.instantiateStreaming(data, go.importObject);

go.run(result.instance);

返回它正常工作!.

但是,每当我尝试调用 add 函数时,都会收到 TypeError:无法读取Welcome.getWasm 上未定义的属性"add",因为这两个result.exports result.instance.exports 不包含我的功能.我也尝试大写Go函数,但无济于事.

However, whenever I try to invoke the add function, I receive TypeError: Cannot read property 'add' of undefined at Welcome.getWasm, because both result.exports, result.instance.exports do not contain my function. I also tried capitalizing the Go function, but at no avail.

因此,我开始怀疑是什么问题– 是否甚至可以从Javascript调用随机Go函数?还是只能调用默认的 main()功能?

Thus, I started wondering what could be a problem – is it even possible to call a random Go function from Javascript? Or can I only call the default main() function?

推荐答案

是的,有可能.您可以将函数导出"到全局上下文(即浏览器中的窗口,在nodejs中为全局):

Yes, it is possible. You can "export" a function to the global context (i.e. window in browser, global in nodejs):

js.Global().Set("add", js.FuncOf(addFunction))

其中"add"是可用于从Javascript(window.add)调用函数的名称,"addFunction"是Go代码中位于主代码旁边的Go函数.

Where "add" is the name that you can use to call the function from Javascript (window.add) and "addFunction" is a Go function in your Go code, next to your main.

请注意,"addFunction"必须遵循该方法签名:

Note that "addFunction" must follow that method signature:

package main

import (
    "syscall/js"
)

func addFunction(this js.Value, p []js.Value) interface{} {
    sum := p[0].Int() + p[1].Int()
    return js.ValueOf(sum)
}

func main() {
    c := make(chan struct{}, 0)

    js.Global().Set("add", js.FuncOf(addFunction))

    <-c
}

在"go.run(result.instance);"之后您可以运行.

After "go.run(result.instance);" you can run.

go.run(result.instance);
add(100,200);

这篇关于是否可以从JS显式调用导出的Go WebAssembly函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆