dongroufan6846 2019-05-31 15:45
浏览 487

是否可以从JS显式调用导出的Go WebAssembly函数?

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

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
}

I can only invoke the main function:

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);

which returns it works! as expected.

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.

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?

  • 写回答

1条回答 默认 最新

  • douna1892 2019-08-01 09:36
    关注

    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))
    

    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.

    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
    }
    

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

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试