关于cgo:是否可以在go共享库中返回指向结构的指针?

Is it possible to return pointers to structs in go shared libraries?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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端访问该结构,我将在运行侧提供帮助程序(我将提供一个示例),该例程将指向该结构的指针作为参数。不幸的是,以上代码无法编译:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,它们工作正常。

有什么办法解决吗?


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

Go struct types are not supported; use a C struct type.

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