Hello all
So, if you look up documentation on CGO, in general, you will find that this is the convention that you should use if you want to call a C function and pass a string that will not be retained:
cStr := C.CString(goStr)
defer C.free(unsafe.Pointer(cStr))
C.SomeCFunction(cStr)
If you are doing this a lot, like for example specifying a bunch of configuration options, all the overhead of converting the string can get really distracting. In my opinion, I think something like this would be ideal:
func toCString(s string) *C.char {
buf := append([]byte(s), 0)
return (*C.char)(unsafe.Pointer(&buf[0]))
}
C.SomeCFunction(toCstring(goStr))
Manually creating the C string with null terminator, and using unsafe.Pointer seems to work alright, and is really convenient to use.
So the question is, am I missing some critical flaw, or I'm just tricking myself into thinking this is safe(ish)? If not, then why is the defer C.free(unsafe.Pointer(cStr)) patter prescribed so commonly?
Thanks :)