问题
I want to copy a Go string into a char * via CGO.
Am I allowed to do this something like this?
func copy_string(cstr *C.char) {
str := "foo"
C.GoString(cstr) = str
}
回答1:
According to the cgo documentation you need to use the C.CString function to convert a Go string to a C string:
cstr = C.CString(str)
Be aware that C.CString function allocates the memory for you, but won't release it, so it is your responsability to freed the memory with a call like:
C.free(unsafe.Pointer(cstr))
来源:https://stackoverflow.com/questions/39023475/how-do-i-copy-a-go-string-to-a-c-char-via-cgo-in-golang