Search code examples
cstructgocgo

Is it possible to write C functions that modify structs of types defined in Go code?


This is a follow-up to this question. I made an assumption there that might not be true, which is why I am explicitly asking about it. Because I forgot to ask if this is actually possible, I have already filed issue #8114 about this.


With cgo, it is possible to have Go code operate on C types, like this:

package foo

//#include <sys/stat.h>
import "C"

func fileSizeFromStat(stat *C.struct_stat) int64 {
    return int64(stat.st_size)
}

Is the reverse possible? I.e. writing C functions that operate on go types? The concrete point of this is outlined in the question linked above; I want to marshall C structures that cannot be accessed from Go code, either because they use unions or bitfields or because their alignment makes them incompatible with Go code.


Solution

  • As far as I know, no, you can't.

    But you could use something ugly like https://github.com/OneOfOne/go-nfqueue/blob/master/nfqueue.go#L130 where you export a Go function that takes a lot of pointers and construct your Go struct in go.