I understand the rule Go code may pass a Go pointer to C provided the Go memory to which it points does not contain any Go pointers. But something wired happened while I pass parameters to C functions.
Code example 1 & 2 are sample codes for the problem.
In the code example 1 I passed &f.a
to the C function and go runtime captured cgo argument has Go pointer to Go pointer
error. I think no go pointers is in f.a
.
And in code example 2 I changed attribute a to a point and the code could run peacefully.
I didn’t see any big differences between example 1 and 2. Why code exapmle 1 panic?
// code exapmle 1
1 package main
1
2 /*
3 #include <stdio.h>
4
5 void nothing(void *x) {
6 }
7 */
8 import "C"
9 import (
10 "unsafe"
11 )
12
13 type foo struct {
14 p *int
15 a int
16 }
17
18 func main() {
19 f := &foo{}
20 b := 10
21 f.p = &b
22 f.a = b
23 C.nothing(unsafe.Pointer(&f.a))
24 }
output of code example 1:
panic: runtime error: cgo argument has Go pointer to Go pointer
goroutine 1 [running]:
main.main.func1(0xc420010038)
/root/go/src/github.com/winglq/test/pointer/main.go:23 +0x96
main.main()
/root/go/src/github.com/winglq/test/pointer/main.go:24 +0x7f
// code exapmle 2
1 package main
1
2 /*
3 #include <stdio.h>
4
5 void nothing(void *x) {
6 }
7 */
8 import "C"
9 import (
10 "unsafe"
11 )
12
13 type foo struct {
14 p *int
15 a *int
16 }
17
18 func main() {
19 f := &foo{}
20 b := 10
21 f.p = &b
22 f.a = &b
23 C.nothing(unsafe.Pointer(f.a))
24 }