Can I pass *[]string
to C from Go and then append
to the string slice, or is it violating the pointer passing spec?
Go code may pass a Go pointer to C, provided the Go memory to which it points does not contain any Go pointers.
Example code:
package main
/*
extern void go_callback(void*, char*);
static inline void callback(void* stringSliceGoPointer) {
go_callback(stringSliceGoPointer, "foobar");
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
a := make([]string, 0)
C.callback(unsafe.Pointer(&a))
fmt.Println(a[0]) // outputs foobar
}
//export go_callback
func go_callback(stringSliceGoPointer unsafe.Pointer, msg *C.char) {
slice := (*[]string)(stringSliceGoPointer)
*slice = append(*slice, C.GoString(msg))
}