Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

cgo

I'm experimenting with using Go for creating dlls in Windows that I can import into Python but I'm having some issues with exporting functions that return a pointer to a Go struct. The following is a very stripped down example:

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() {
}

Note I also create a pointer type hoping this would end up as a simple handle on the C side. For the C side to access the struct I would provide helper routines (I provide one example) on the go side that would take a pointer to the struct as an argument. Unfortunately, the above code doesn't compile:

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
}

Is this a limitation of Go? I've tried simple return values such as int and floats and they work ok.

Is there any way around it?


1 Answers

Based on https://golang.org/cmd/cgo/#hdr-C_references_to_Go:

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

Also check out the following Github issue: https://github.com/golang/go/issues/18412

like image 106
Jerome Meyer Avatar answered Dec 07 '25 22:12

Jerome Meyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!