dqxmf02844 2019-08-18 08:42
浏览 113
已采纳

如何将go指针作为wasm上下文数据传递?

I'm looking at wasmer go-ext-wasm example code /go-ext-wasm/wasmer/test/imports.go learning about setting context data. I want to pass a pointer as contextData, what's the best way to do this?

//export sum
func sum(context unsafe.Pointer, x int32, y int32) int32 {
    instanceContext := wasm.IntoInstanceContext(context)
    t := *(*int)(instanceContext.Data())
    log.Print("t: ", t)
    return x + y
}

func testInstanceImport(t *testing.T) {
    imports, err := wasm.NewImports().Namespace("env").Append("sum", sum, C.sum)
    assert.NoError(t, err)

    instance, err := wasm.NewInstanceWithImports(getImportedFunctionBytes("examples", "imported_function.wasm"), imports)
    defer instance.Close()
    assert.NoError(t, err)

    bar := int(2)
    barPtr := &bar

    data := unsafe.Pointer(&bar)
    instance.SetContextData(data)
    log.Printf("bar %v, barPtr %v", bar, barPtr)
    add1, exists := instance.Exports["add1"]
    assert.Equal(t, true, exists)

    result, err := add1(1, 2)
    log.Print("Result: ", result)
    assert.Equal(t, wasm.I32(4), result)
    assert.NoError(t, err)
}

Which gives me the expected value of 2 for context in the sum function. However when I change data := unsafe.Pointer(&bar) to data := unsafe.Pointer(&barPtr) I get a: runtime error: cgo argument has Go pointer to Go pointer error.

It works when I run it with GODEBUG=cgocheck=0 Should I be concerned running with this flag? Is what I'm trying to do a bad idea? I have a struct that contains a pointer that I need to pass as contextData, is using the GODEBUG=cgocheck=0 a bad idea?

  • 写回答

1条回答 默认 最新

  • doupao5296 2019-08-19 07:40
    关注

    I found the solution here: cgo: Go pointers in Go memory The Registry Example (Alternative) solves my issue. Thanks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急