Closed
Description
Noticed from http://stackoverflow.com/questions/35673161/convert-go-byte-to-a-c-char#35675259
These two very similar programs, but one crashes while other succeeds.
$ go version
go version devel +387d5b8 Sat Feb 13 17:33:22 2016 +0000 linux/amd64
$ cat nocrash.go
package main
import (
"bytes"
"log"
"unsafe"
)
/*
void the_function(const void *data, int nbytes) {
}
*/
import "C"
func main() {
buf := new(bytes.Buffer)
_, err := buf.Write([]byte{1, 2, 3})
if err != nil {
log.Fatal(err)
}
b := buf.Bytes()
C.the_function(unsafe.Pointer(&b[0]), C.int(buf.Len()))
}
$ go run nocrash.go
$ cat crash.go
package main
import (
"bytes"
"log"
"unsafe"
)
/*
void the_function(const void *data, int nbytes) {
}
*/
import "C"
func main() {
buf := new(bytes.Buffer)
_, err := buf.Write([]byte{1, 2, 3})
if err != nil {
log.Fatal(err)
}
C.the_function(unsafe.Pointer(&(buf.Bytes())[0]), C.int(buf.Len()))
}
a@spot: a $ go run crash.go
panic: runtime error: cgo argument has Go pointer to Go pointer
goroutine 1 [running]:
main._cgoCheckPointer0(0x4c5a60, 0xc820054094, 0x0, 0x0, 0x0, 0x0)
command-line-arguments/_obj/_cgo_gotypes.go:40 +0x4d
main.main()
/home/a/src/a/crash.go:21 +0x1f8
exit status 2
$
Given current bytes.Buffer implementation I don't understand why crash.go crashes.
Alex