【问题标题】:Is it possible to return pointers to structs in go shared libraries?是否可以在 go 共享库中返回指向结构的指针?
【发布时间】:2019-12-07 07:06:42
【问题描述】:

我正在尝试使用 Go 在 Windows 中创建可以导入 Python 的 dll,但是在导出返回指向 Go 结构的指针的函数时遇到了一些问题。以下是一个非常精简的示例:

package main

import "C"

type data struct {
    value1, value2 int
}

type PData *data

//export Callme
func Callme() PData {
    var d PData = new (data)
    return d
}

//export getValue1
func getValue1 (st PData) int {
   return st.value1
}

func main() {
}

注意,我还创建了一个指针类型,希望这最终会成为 C 端的简单句柄。为了让 C 端访问结构,我将在 go 端提供辅助例程(我提供一个示例),它将指向结构的指针作为参数。不幸的是,上面的代码没有编译:

go build -o main.dll -buildmode=c-shared .\main.go
# command-line-arguments
.\main.go:5:11: Go type not supported in export: struct {
     value1, value2 int
}
.\main.go:5:11: Go type not supported in export: struct {
    value1, value2 int
}
.\main.go:5:11: Go type not supported in export: struct {
    value1, value2 int
}
.\main.go:5:11: Go type not supported in export: struct {
    value1, value2 int
}

这是 Go 的限制吗?我尝试过简单的返回值,例如 int 和 floats,它们工作正常。

有什么办法吗?

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    基于https://golang.org/cmd/cgo/#hdr-C_references_to_Go:

    不支持 Go 结构类型;使用 C 结构类型。

    还可以查看以下 Github 问题: https://github.com/golang/go/issues/18412

    【讨论】:

    • 这就是我所担心的。我想我可以通过将 go 指针映射到可以返回到 C 端并用作句柄的简单整数来解决它。我认为垃圾收集器不会产生任何副作用。
    猜你喜欢
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 2018-10-09
    相关资源
    最近更新 更多